【问题标题】:Alternate between titles and paragraphs with itextsharp使用 itextsharp 在标题和段落之间交替
【发布时间】:2015-03-17 15:17:44
【问题描述】:

我正在尝试使用 itextsharp 编写 pdf 文档,但我不会在两种样式之间交替:标题和段落。

我尝试过这样的事情:

Paragraph title= new Paragraph();
title.Alignment = Element.ALIGN_CENTER;
title.Font = FontFactory.GetFont("Arial", 32);
title.Add("\nTitle 1\n\n");
pdfDoc.Add(title);


Paragraph paragraph = new Paragraph();
paragraph.Alignment = Element.ALIGN_LEFT;
paragraph.Font = FontFactory.GetFont("Arial", 12);
paragraph.Add("Lorem ipsum dolor sit amet \n");
pdfDoc.Add(paragraph);


title.Add("\nTitle 2\n\n");
pdfDoc.Add(title);
paragraph.Add("Consectetur adipiscing elit \n");
pdfDoc.Add(paragraph);

但看起来我需要在添加新文本之前清除内容。是否可以只清除文本或者我必须为每个段落创建新变量?希望不会……

【问题讨论】:

    标签: c# asp.net pdf-generation itextsharp


    【解决方案1】:

    解决问题的一种方法是像这样更改代码:

    Font titleFont = FontFactory.GetFont("Arial", 32);
    Font regularFont = FontFactory.GetFont("Arial", 36);
    Paragraph title;
    Paragraph text;
    title = new Paragraph("Title", titleFont);
    title.Alignment = Element.ALIGN_CENTER;
    pdfDoc.Add(title);
    text = new Paragraph("Lorem ipsum dolor sit amet", regularFont);
    pdfDoc.Add(text);
    title = new Paragraph("Title 2", titleFont);
    title.Alignment = Element.ALIGN_CENTER;
    pdfDoc.Add(title);
    text = new Paragraph("Consectetur adipiscing elit", regularFont);
    pdfDoc.Add(text);
    

    如果添加文本后内容会消失,这将被视为严重错误。这意味着使用过一次的对象不能再被重用。简而言之:在您的问题中,您要求 iTextSharp 的开发人员引入一个错误......

    通常,创建一个单独的类来定义所有使用的Font 对象。使用getTitle()getText() 等自定义方法创建一个辅助类也是一个好主意,类似于PojoToElementFactory 类(注意POJO 代表Plain Old Java Object。原始代码编写在Java,真的是……你的)。

    使用\n 引入换行符是一个不好的 主意。为什么不使用 leadingspacing beforespacing after 等属性来定义行之间的空白? p>

    【讨论】:

    • 它按我的意愿工作,谢谢!我使用 \n 是因为我还在学习并且我什么都不知道,但我会尝试将它替换为之前/之后的间距,它看起来更干净。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 2015-06-23
    • 2017-05-06
    • 2015-04-04
    • 1970-01-01
    相关资源
    最近更新 更多