【问题标题】:iTextSharp preserve html formatting on pdfiTextSharp 在 pdf 上保留 html 格式
【发布时间】:2013-09-13 20:25:08
【问题描述】:

我在 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 的代码

标签: asp.net-mvc ckeditor itextsharp


【解决方案1】:

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

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

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

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

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

【讨论】:

猜你喜欢
  • 2011-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 2011-08-11
  • 2011-02-18
  • 1970-01-01
相关资源
最近更新 更多