[英]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.