目前我在asp.net c#中使用Restful服务,以下是我获得的 pdf
字符串返回,我想将其转换并保存为。 pdf
文件。我该怎么办?
static string HttpGet(string url)
{
HttpWebRequest req = WebRequest.Create(url)
as HttpWebRequest;
string result = null;
using (HttpWebResponse resp = req.GetResponse()
as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}
return result;
}
/****************************** result returned ******************************/
%PDF-1.3
%����
3 0 obj
<<
/Linearized 1
/O 5
/H [ 526 186 ]
/L 47163
/E 46840
/N 1
/T 47053
>>
endobj
xref
3 11
0000000016 00000 n
0000000436 00000 n
0000000712 00000 n
0000000957 00000 n
0000001056 00000 n
0000001078 00000 n
0000046475 00000 n
0000046502 00000 n
0000046611 00000 n
0000046725 00000 n
0000000526 00000 n
trailer
<<
/Size 14
/Info 1 0 R
/Root 4 0 R
/Prev 47044
>>
startxref
0
%%EOF
4 0 obj
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj
13 0 obj
<<
/Length 104
/P 0
/S 46
>>
stream
答案 0 :(得分:8)
using (Stream stream = ... fetch the stream from somewhere)
{
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
File.WriteAllBytes("foo.pdf", buffer);
}
如果此RESTful服务与HTTP对话,您可以使用WebClient:
using (var client = new WebClient())
{
client.DownloadFile("http://example.com/api", "foo.pdf");
}
答案 1 :(得分:1)
我有这种情况,我解决了使用 iTextSharp 生成pdf并保存在磁盘中。
public void GeneratePdf(string htmlPdf)
{
var pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
var htmlparser = new HTMLWorker(pdfDoc);
using (var memoryStream = new MemoryStream())
{
var writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
pdfDoc.Open();
htmlparser.Parse(new StringReader(htmlPdf));
pdfDoc.Close();
byte[] bytes = memoryStream.ToArray();
File.WriteAllBytes(@"C:\file.pdf", bytes);
memoryStream.Close();
}
}
答案 2 :(得分:-1)