![](/img/trans.png)
[英]Using iText7 (Java) to add a table to an existing PDF and continue on additional pages
[英]Using iText7 to add a table in a specific page of an existing PDF
我正在嘗試將動態創建的表添加到動態創建的現有PDF。 我想將表格“追加”到現有PDF 最后一頁的特定位置。
我當前的代碼基於Uladzimir Asipchuk在此線程上給出的答案,它看起來像這樣:
public byte[] completePDF(byte[] originalPDF){
ByteArrayInputStream is = new ByteArrayInputStream(originalPDF);
ByteArrayOutputStream os = new ByteArrayOutputStream();
PdfDocument pdfDoc;
try {
pdfDoc = new PdfDocument(new PdfReader(is), new PdfWriter(os));
final Document doc = new Document(pdfDoc);
//FAKE TABLE TO TEST
Table table = new Table(UnitValue.createPercentArray(new float[] {10f,90f}));
for (int i = 0; i<150; i++){
table.addCell(new String(new Integer(i).toString()));
table.addCell("FAKE DATA");
}
doc.setRenderer(new DocumentRenderer(doc) {
@Override
protected LayoutArea updateCurrentArea(LayoutResult overflowResult) {
int lastPage = doc.getPdfDocument().getNumberOfPages();
LayoutArea area = super.updateCurrentArea(overflowResult);
if (area.getPageNumber() == lastPage) {
PdfDocumentContentParser parser = new PdfDocumentContentParser(doc.getPdfDocument());
TextMarginFinder finder = parser.processContent(lastPage, new TextMarginFinder());
area.getBBox().decreaseHeight(finder.getTextRectangle().getHeight() + 30);
}
return area;
}
});
doc.add(table);
doc.close();
} catch (Exception e) {
return null;
}
return os.toByteArray();
}
這段代碼幾乎可以實現我想要的功能(根據表的大小添加新頁面,並且最后一頁的表位置在該頁面的文本之后開始),但是我不知道要強制該表開始獲取在最后一頁上繪制。
有可能嗎? 任何幫助將不勝感激。
謝謝!
我自己找到了解決方案,我真的很了解。 我將其發布,以防萬一有人遇到相同的問題:
if (area.getPageNumber() == lastPage) {
PdfDocumentContentParser parser = new PdfDocumentContentParser(doc.getPdfDocument());
TextMarginFinder finder = parser.processContent(lastPage, new TextMarginFinder());
area.getBBox().decreaseHeight(finder.getTextRectangle().getHeight() + 30);
} else if (area.getPageNumber() < lastPage){
area.getBBox().decreaseHeight(doc.getPdfDocument().getDefaultPageSize().getHeight());
}
return area;
這樣,表格就緊接在PDF最后一頁的文本結尾之后被“追加”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.