我使用OpenPDF在Java中创建了一个PDF文件,并插入了一个段落。问题是我想把它放在中间,而不是左边。这是如何做到的呢?
第二个问题:我如何在测试中放置一个带有特定格式的单词?
例如:“Helloand迎宾”(欢迎应为粗体)
这是我的密码:
Document document = new Document();
String PDFPath = "output.pdf";
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDFPath));
Font font_bold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD, Color.BLACK);
Font font_normal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL, Color.BLACK);
Paragraph p1 = new Paragraph("Ordonnance", font_bold);
document.open();
document.add(p1);
document.close();发布于 2021-07-18 16:19:59
如果希望以段落为中心,则需要定义对齐方式:
p1.setAlignment(Element.ALIGN_CENTER);
要将格式应用于文本的某些部分,可以将其分成几个块。Chunk in OpenPDF是一个具有特定字体的字符串。而不是向段落中添加一个String (未格式化的),而是添加一个象new Chunk("Hello and ", fontNormal)这样的块对象,它定义了要使用的文本和字体。
以下是您根据问题想要做的事情的代码:
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
document.open();
Font fontNormal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL);
Font fontBold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD);
Paragraph p1 = new Paragraph();
p1.setAlignment(Element.ALIGN_CENTER);
p1.add(new Chunk("Hello and ", fontNormal));
p1.add(new Chunk("welcome", fontBold));
document.add(p1);
document.close();结果如下:

发布于 2021-04-24 16:21:29
您的第一行有一些奇怪的声明,但这应该有效:
Document document = new Document();
String PDFPath = "D:\\test.pdf";
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDFPath));
Font font_bold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD, Color.BLACK);
Font font_normal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL, Color.BLACK);
Paragraph p1 = new Paragraph("Ordonnance", font_bold);
p1.setAlignment(Element.ALIGN_CENTER);
document.open();
document.add(p1);
document.close();你只需要设置段落的对齐
https://stackoverflow.com/questions/67244006
复制相似问题