使用itextsharp将HTML转换为PDF

raj*_*aje 6 html css c# pdf asp.net

当使用itextsharp样式ist 将html转换为pdf时,使用css为网页应用转换后的pdf无法正常工作.

这是我的css代码:

<style type="text/css">
       .cssformat
            {
                width:300px;
                height:200px;
                border:2px solid black;
                background-color:white; 
                border-top-left-radius:60px 90px; 
                border-bottom-right-radius:60px 90px;
        }                
        </style>
Run Code Online (Sandbox Code Playgroud)

这是我的HTML代码:

      <div id="divpdf" runat="server">
        <table id="tid" runat="server">
        <tr>
        <td>
       <asp:Label ID="Label1" runat="server" Text="this is new way of pdf" CssClass="cssformat"></asp:Label>
        </td>
        </tr>
        </table>
        </div>
Run Code Online (Sandbox Code Playgroud)

以下是我用c#试过的内容:

 Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        Document pdfDoc = new Document(PageSize.A4, 60f, 80f, -2f, 35f);
        divpdf.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());   
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        hw1.Parse(new StringReader(sttt));
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
        sw.Close();
        sr.Close();
        hw.Close();
Run Code Online (Sandbox Code Playgroud)

And*_*ard 5

我很难使用iTextSharp将HTML转换为PDF,并最终放弃了,因为我无法获得看上去与HTML5 / CSS3页面100%相同的转换后的PDF。因此,我为您提供了最终对我有用的替代方案。

当您不准备付费购买商业图书馆时,几乎没有可用的选择。我的一位客户提出相同的要求(从HTML转换为PDF),但又不想为任何第三方工具付费,因此我必须制定一个计划。这是我所做的,不是最好的解决方案,但已完成工作

我下载了最新版本的wkhtmltopdf。不幸的是,当转换为PDF时,wkhtmltopdf工具没有显示我的HTML中嵌入的某些Google图形。因此,我还使用了随附的wkhtmltoimage工具将其转换为PNG,该PNG可以正常运行并显示所有图形。然后,我下载了最新版本的imagemagick,并将PNG转换为PDF。我使用C#自动化了此过程。

不幸的是,这不是最优雅的解决方案,因为您必须执行两次转换并做一些工作来使所有操作自动化,但这是我能想到的最好的解决方案,它给了我理想的结果和质量。

当然,有很多商业软件可以更快更好地完成工作。

附带说明:

我必须转换的网页是使用Bootstrap的第3版开发的HTML5和CSS3,其中包含一些Google图形和图表。一切都已转换,没有任何问题。