0

当我尝试使用itext将 Html 转换为 Pdf 时。它只显示空白页,缺少 pdf 内容。请帮助

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\appadmin\\git\\SoharPDF\\template\\sample2.pdf"));
    document.open();
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream("C:\\Users\\appadmin\\git\\SoharPDF\\template\\Form W9_out.html"), Charset.forName("UTF-8"));
    document.close();

谢谢。

4

1 回答 1

0

试试这个方法:

public override string GenerateReport()
    {
        string sFileLocation = m_sFileName == null ? (Path.GetTempFileName() + ".pdf") : (Path.GetTempPath() +  m_sFileName);
        
        FileStream aNewFileStream = new FileStream(sFileLocation, FileMode.Create);                                                
        Byte[] bytes;
        using (var ms = new MemoryStream())
        {
            using (Document document = new Document(PageSize.A4, PdfEventsBase.PAGE_MARGIN_LEFT, PdfEventsBase.PAGE_MARGIN_RIGHT, PdfEventsBase.PAGE_MARGIN_TOP, PdfEventsBase.PAGE_MARGIN_BOTTOM))
            {
                using (PdfWriter aPdfWriter = PdfWriter.GetInstance(document, aNewFileStream))
                {
                    aPdfWriter.PageEvent = new PdfEventsPageTemplate(null, Sites.PAA, null);
                    document.Open();

                    using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(m_sCSS)))
                    {
                        using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(m_sHTML)))
                        {
                            //Parse the HTML
                            iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(aPdfWriter, document, msHtml, msCss);
                        }
                    }
                    document.Close();
                }
            }
            bytes = ms.ToArray();
        }
        
        //System.IO.File.WriteAllBytes(sFileLocation, bytes);
        return sFileLocation;
    }
于 2020-07-13T11:56:08.267 回答