itextsharp - 将页面转换为PDF并自动保存到临时文件夹而无需打开下载对话框

时间:2016-04-01 15:00:49

标签: c# asp.net asp.net-web-api itextsharp

早上好,我发现示例代码让我使用itextsharp库将当前页面保存为pdf,然后自动将其保存到站点内的临时文件夹中。但它一直做的一件事是它一直触发浏览器提示我下载或保存文件。该文件已保存在临时文件夹中,我只是想以某种方式禁用该浏览器对话框下载。请指教。任何帮助都非常感谢。 谢谢

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=RequestSummaryReport.pdf");
    HttpContext.Current.Response.Charset = "";
    HttpContext.Current.Response.ContentType = "application/pdf";

    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document(PageSize.A3, 45, 5, 5, 5);
    //PdfWriter writer = PdfWriter.GetInstance(pdfDocument, Response.OutputStream);
    PdfWriter writer = PdfWriter.GetInstance(pdfDocument, new FileStream(Server.MapPath("~/temps/") + "mypdf.pdf", FileMode.CreateNew));

    pdfDocument.Open();

    HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
    htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
    ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);

    IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDocument, writer)));

    XMLWorker worker = new XMLWorker(pipeline, true);
    XMLParser xmlParse = new XMLParser(true, worker);

    this.Page.RenderControl(htw);
    StringReader sr = new StringReader(sw.ToString());
    xmlParse.Parse(sr);
    xmlParse.Flush();
    pdfDocument.Close();
    //Response.Write(pdfDocument);
    Response.End();

1 个答案:

答案 0 :(得分:1)

所以你想把它保存在服务器上?是否要在不提示用户保存的情况下将pdf显示到浏览器?也许this之前关于SO的帖子的答案可能有所帮助。我记得行为可能因浏览器(IE,Chrome,Firefox,Safari)而异。使用时:

Response.AddHeader("Content-Disposition", "inline;filename=somefile.ext")

浏览器将尝试将pdf呈现给浏览器。

如果删除以下代码行,浏览器不应提示您保存文件:

HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=RequestSummaryReport.pdf");