[英]Why I can't vertically print this String with iText?
我没有使用iText的丰富经验,我有以下问题。
我必须在页面中垂直放置一个短语 (一个简单的字符串,我认为在我的情况下也可以使用Chunk )。
所以我在官方的iText文档中找到了这个教程: http : //itextpdf.com/examples/iia.php?id = 202
这是我的代码:
private static void printPdf() {
/** The resulting PDF file: */
String result = "D:/MYCOMPANY/massive_pdf_print.pdf";
// STEP 1 Creazione del documento in formato A4 e senza margini:
com.itextpdf.text.Document document = new com.itextpdf.text.Document(com.itextpdf.text.PageSize.A4, 0, 0, 0, 0);
try {
/* STEP 2 Constructs a PdfWriter.
document: The PdfDocument that has to be written.
os: The OutputStream the writer has to write to
*/
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result));
// STEP 3:
document.open();
// STEP 4:
//document.add(new Paragraph("Hello World!"));
VerticalText vt = new VerticalText(writer.getDirectContent());
vt.addText(new Phrase("Hello World !!!"));
vt.go();
// STEP 5:
document.close();
}catch (DocumentException ex){
ex.printStackTrace();
}
catch (IOException ex){
ex.printStackTrace();
}
}
好的问题是,当尝试执行此行时:
document.close();
抛出以下异常:
Exception in thread "main" ExceptionConverter: java.io.IOException: The document has no pages.
at com.itextpdf.text.pdf.PdfPages.writePageTree(PdfPages.java:113)
at com.itextpdf.text.pdf.PdfWriter.close(PdfWriter.java:1217)
at com.itextpdf.text.pdf.PdfDocument.close(PdfDocument.java:777)
at com.itextpdf.text.Document.close(Document.java:398)
at mainPkg.Main.printPdf(Main.java:123)
at mainPkg.Main.main(Main.java:78)
Process finished with exit code 1
为什么? 我错过了什么? 如何解决这个问题并垂直打印我的“Hello World !!!” 串?
编辑1:
这是我在修改插入的代码后看到生成的PDF的方法:
vt.setVerticalLayout(390, 570, 540, 12, 30);
正如您所看到的那样,文本没有垂直对齐,但似乎是水平的边距。 为什么? 我错过了什么?
TNX
您没有定义任何尺寸。
在我所提到的书的例子中,有这一行:
vt.setVerticalLayout(390, 570, 540, 12, 30);
这些坐标定义垂直列的位置,请参阅setVerticalLayout()
方法:
由于您没有定义这些值,因此iText不知道在何处添加文本,因此不会添加任何文本并且“文档没有页面”。
更新:
尽管最初的问题得到了充分的回答,但并未被接受。 而是改变了问题。 这在StackOverflow上不是正确的行为:应该发布一个新问题。
此外,这两个问题,原始问题和改编版问题都证明了对文件的不尊重。 我的书中有一个例子,然后那个例子被肢解,然后我被问到:为什么这不起作用。
第一次切割包括删除基本线。 第二次切割表明,为支持该示例而编写的文档被忽略了。
在编写垂直文本时,您需要使用特定的编码: Identity-V
。 正如书中所解释的, Identity-H
用于水平书写系统,而Identity-V
用于垂直书写系统。 您正在使用水平书写编码,期望它垂直写入文本...
如何解决这个问题? 通过使用VTE示例中显示的Identity-V
:
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
BaseFont bf = BaseFont.createFont(
FONT, BaseFont.IDENTITY_V, BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, 20);
VerticalText vt = new VerticalText(writer.getDirectContent());
vt.setVerticalLayout(559, 806, 770, 29, 18);
vt.addText(new Phrase("Hello World !!!", font));
vt.go();
document.close();
}
重要的参数是BaseFont.IDENTITY_V
。 请注意,此参数不能与每种字体结合使用。 例如:它不适用于Helvetica。 在我的例子中,我使用了FreeSans:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.