Html到pdf转换器

时间:2013-07-08 07:49:56

标签: asp.net c#-4.0 html-to-pdf

我的要求是将Html转换为pdf转换器,我通过代码执行此操作。但现在我的要求是如何保存到文件夹中。

 Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Certificate.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    System.Text.StringBuilder ss = new System.Text.StringBuilder(CertificateHtml);
    StringWriter sw = new StringWriter(ss);
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();

    Response.Write(pdfDoc);
    Response.End();

请帮忙。

2 个答案:

答案 0 :(得分:1)

您可以在Response.Write(pdfDoc);

之后尝试此操作
Response.Write(pdfDoc);

FileStream fs = new FileStream(Server.MapPath("~/pdfFolder/pdfFile.pdf"), FileMode.Create);
StreamReader sr = new StreamReader(Response.OutputStream);
byte[] data = new byte[Response.OutputStream.Length];
Response.OutputStream.Read(data, 0, data.Length);
fs.Write(data, 0, data.Length);

fs.Flush();
fs.Close();

除此之外,您正在使用的第三方工具或PDF生成也可能为您提供此操作的功能。

答案 1 :(得分:1)

使用它。

string fileName = DateTime.Now.Ticks.ToString();
string filepath = Server.MapPath("~") + fileName + ".pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/pdf";
Response.TransmitFile(filepath);
Response.End();