【问题标题】:Can't make text bold in pdfpdf中的文本不能加粗
【发布时间】:2015-11-03 21:25:58
【问题描述】:

我想用 pdf 粗体显示总和。我尝试了下一个:

var phraseTotal = new Paragraph();
phraseTotal.Font.SetStyle(Font.BOLD);
phraseTotal.Add(new Chunk(string.Format("Total earned for period {0} - {1} : ", invoice.FromDate.ToShortDateString(), invoice.ToDate.ToShortDateString())));
phraseTotal.Add(new Chunk("£" + Math.Round(invoice.TotalAmount / 100.0, 2, MidpointRounding.AwayFromZero)));

list.Add(phraseTotal);

还尝试在段落中添加一些字体...尝试将段落更改为短语...

但这个总和总是不可见或不呈现在 pdf 中。


更新:问题在列表中。如果我将相同的应用于不在列表中的对象 - 它是粗体。

【问题讨论】:

  • 仅供参考 - WKHTMLToPDF,通过 Codaxy 和从 HTML 转换是正确的方法。它也是免费的。在我找到 WKHTMLToPDF 之前,我花了一个月左右的时间在各种方法上苦苦挣扎。我再也不会使用其他任何东西了。
  • @Mr.B WKHTMLToPDF 也有一些问题,不过现在我用的是itextSharp
  • 我也使用了 ITextSharp。如果您从头开始,ITextSharp 很好,但它不正确地遵守 CSS。您必须嵌入样式表。而不是构建像段落这样的新东西。最简单的方法是让它在 HTML 中看起来正确,然后通过转换器进行处理。
  • @Mr.B 我同意,但目前我只需要将文本加粗......我现在没有时间重写:(

标签: c# pdf fonts itext


【解决方案1】:

我会走这条路,而不是费心编写代码来做到这一点:

private MemoryStream createPDF(string html)
{
    MemoryStream msOutput = new MemoryStream();
    TextReader reader = new StringReader(html);

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 30, 30);            

    // step 2:
    // we create a writer that listens to the document
    // and directs a XML-stream to a file
    PdfWriter writer = PdfWriter.GetInstance(document, msOutput);

    // step 3: we create a worker parse the document
    HTMLWorker worker = new HTMLWorker(document);

    // step 4: we open document and start the worker on the document
    document.Open();
    worker.StartDocument();

    // step 5: parse the html into the document
    worker.Parse(reader);

    // step 6: close the document and the worker
    worker.EndDocument();
    worker.Close();
    document.Close();

    return msOutput;
}

【讨论】:

  • HTMLWorker 已被弃用。在新代码中使用它可能不是一个好主意。
【解决方案2】:
Chunk c1 = new Chunk("Concentrate:", new Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 11, Font.BOLD, BaseColor.BLUE)));
Chunk c2 = new Chunk("In order to remember something you need to learn it. Learning is possible only if you pay enough attention to it. You will retain information for a longer period of time only if you concentrate properly at the time of learning.", new Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 11, Font.NORMAL, BaseColor.BLUE)));

Pharagraph p2 = new Pharagraph();
p2.Add(c1);
p2.Add(c2);

ListItem firstRecommend = new ListItem(p2);

此示例来自此答案https://stackoverflow.com/a/9227686/3917754

我能够产生的问题是因为我没有创建新的ListItem,而是立即将Paragraph 添加到列表中。使用List Item 一切正常。

【讨论】:

    猜你喜欢
    • 2014-02-10
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2011-06-03
    • 2012-12-24
    • 1970-01-01
    相关资源
    最近更新 更多