iTextSharp 保留 pdf 上的 html 格式



我正在使用一些基本的样式,包括ckeditor粗体,斜体等,以允许我的用户为报告编写设置文本样式。

当这个字符串传递给iTextSharp时,我正在删除html,否则html将打印在pdf上。我正在删除它

Regex.Replace(item.DevelopmentPractice.ToString(), @"<[^>]*>|&nbsp;", String.Empty)

有没有办法格式化pdf上的文本以保留粗体但不显示

<strong></strong>

更新

我根据要求在下面提供了完整的代码。

public FileStreamResult pdf(int id)
{
    // Set up the document and the Memory Stream to write it to and create the PDF writer instance
    MemoryStream workStream = new MemoryStream();
    Document document = new Document(PageSize.A4, 30, 30, 30, 30);
    PdfWriter.GetInstance(document, workStream).CloseStream = false;
    // Open the pdf Document
    document.Open();
    // Set up fonts used in the document
    Font font_body = FontFactory.GetFont(FontFactory.HELVETICA, 10);
    Font font_body_bold = FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD);
    Chunk cAreasDevelopmentHeading = new Chunk("Areas identified for development of practice", font_body_bold);
    Chunk cAreasDevelopmentComment = new Chunk(item.DevelopmentPractice != null ? Regex.Replace(item.DevelopmentPractice.ToString(), @"<[^>]*>|&nbsp;", String.Empty) : "", font_body);
    Paragraph paraAreasDevelopmentHeading = new Paragraph();
    paraAreasDevelopmentHeading.SpacingBefore = 5f;
    paraAreasDevelopmentHeading.SpacingAfter = 5f;
    paraAreasDevelopmentHeading.Add(cAreasDevelopmentHeading);
    document.Add(paraAreasDevelopmentHeading);
    Paragraph paraAreasDevelopmentComment = new Paragraph();
    paraAreasDevelopmentComment.SpacingBefore = 5f;
    paraAreasDevelopmentComment.SpacingAfter = 15f;
    paraAreasDevelopmentComment.Add(cAreasDevelopmentComment);
    document.Add(paraAreasDevelopmentComment);
    document.Close();
    byte[] byteInfo = workStream.ToArray();
    workStream.Write(byteInfo, 0, byteInfo.Length);
    workStream.Position = 0;
    // Setup to Download
    HttpContext.Response.AddHeader("content-disposition", "attachment; filename=supportform.pdf");
    return File(workStream, "application/pdf");

这真的不是将HTML转换为PDF的最佳方法 - iText或没有iText。尝试寻找不同的方法,您实际上并没有将HTML转换为PDF,而是使用Chunks将抓取的文本插入PDF。

执行iText HTML2PDF最常见的方法似乎是使用HTMLWorker(我认为在较新版本中可能是XMLWorker),但人们也抱怨这一点;看到这个。看起来您正在使用没有HTML的未转换的iText元素构建PDF,并希望在这些元素中使用HTML,我猜这将非常非常困难。

在链接的 HTML worker 示例中,查看程序的结构。他们进行HTML2PDF转换 - 但如果失败,他们使用其他iText方法创建PDF,如段落和块。他们在那里将 Chunk 设置为也有一些样式。

我想你必须解析传入的 HTML,自己将其划分为块,将 s 转换为带有样式的块,然后才将它们吐到 PDF 上。现在想象一下,使用像 CKE 这样的数据源来做到这一点 - 即使使用非常严格的 ACF,那也将是一场噩梦。如果有人知道除此之外的任何其他方式,我也想知道(我基本上以 CKE 到 PDF 为生)!

您是否有任何选择,例如创建自己的编辑器或使用其他PDF技术?我使用wkhtmltopdf,但我的情况非常不同。我会使用PrinceXML,但它太贵了。

最新更新