简体   繁体   English

如何从网页打印PDF

[英]How to print a PDF from a web page

Does anybody know how to make a print page button print a pdf document? 有人知道如何使打印页面按钮打印pdf文档吗?

At the moment i'm using 目前我正在使用

<a href="javascript:window.print()" class="print_it" title="Print page">Print Page</a>

Obviously that just prints the page though. 显然,这只是打印页面。 I have had to create pdf's for each page and thought it would be easier just to print the pdf instead of the page (Cross browser printing styles is kinda sucking ;). 我不得不为每个页面创建pdf,并认为仅打印pdf而不是页面会更容易(跨浏览器的打印样式有点烂;)。

Any ideas? 有任何想法吗?

There is no standard way to print anything in PDF in any browser, such as on the Windows platform. 没有标准方法可以在任何浏览器(例如Windows平台)上以PDF打印任何内容。 On the Mac, there is always an option to print something as a PDF file, so regular printing will do. 在Mac上,始终可以选择将某些内容打印为PDF文件,因此可以进行常规打印。

I suggest you use Itextsharp. 我建议您使用Itextsharp。 If you are using asp.net c#, this code works for you. 如果您使用的是asp.net c#,则此代码适用于您。 Runs in the server side though. 虽然在服务器端运行。 You can just put the html inside a panel to make it readable in the server. 您可以将html放在面板中以使其在服务器中可读。

    /// import these namespaces 
    using System.IO;
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using iTextSharp.text.html.simpleparser;
    using System.Web.Services;
    using System.Text;

    /// Call this method whenever you need to convert 
    /// the html content inside the panel which runs in the server side. 
    [WebMethod]
    public void ConvertHtmlStringToPDF()
    {
        StringBuilder sb = new StringBuilder(); 
        StringWriter tw = new StringWriter(sb); 
        HtmlTextWriter hw = new HtmlTextWriter(tw); 
        pnlPDF.RenderControl(hw);
        string htmlDisplayText = sb.ToString(); 

        Document document = new Document();
        MemoryStream ms = new MemoryStream();
        PdfWriter writer = PdfWriter.GetInstance(document, ms);
        StringReader se = new StringReader(htmlDisplayText);
        HTMLWorker obj = new HTMLWorker(document);
        document.Open();
        obj.Parse(se);
        // step 5: we close the document
        document.Close();
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=report.pdf");
        Response.ContentType = "application/pdf";
        Response.Buffer = true;
        Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
        Response.OutputStream.Flush();
        Response.End();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM