如何利用iText在(X,Y)的位置添加一个PdfPTable到HTML字符串的文件吗?(How t

2019-10-19 02:53发布

我做的html to pdf conversion利用iText。

我已经使用具有下列内容代码HTMLWorker类 (不推荐):

    String htmlString = "<html><body> This is my Project <table width= '50%' border='0' align='left' cellpadding='0' cellspacing='0'><tr><td>{VERTICALTEXT}</td></tr></table></body></html>";

    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(htmlString ));
    document.close();
    file.close();
}

现在我要替换{VERTICALTEXT}一些字符串动态。

所以,我再添加下面的代码:

PdfPTable table = null;
PdfPCell cell;
cell = new PdfPCell(new Phrase("My Vertical Text"));
cell.setRotation(90);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell);
String verticalLoc  = table.toString(); //this variable should hold the text "My Vertical Text" in 90 degree rotated form.

HashMap<String, String> map = new HashMap<String, String>();
map.put("VERTICALTEXT", verticalLoc);

html = new String(buffer);

for (HashMap.Entry<String, String> e : map.entrySet())
{
    String value = e.getValue() != null ? e.getValue():"";
        html = html.replace("{" + e.getKey() + "}", value);
}

htmlWorker.parse(new StringReader(htmlStr));

在输出:

{VERTICALTEXT}替换com.itextpdf.text.pdf.PdfPTable@41d62bcO

所需的输出:

{VERTICALTEXT}应替换My Vertical Text以90度旋转的形式。

Answer 1:

这是解决想通了和测试 -

Java文件相关的代码:

static PdfWriter writer;
writer = PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
PdfPTable table = new PdfPTable(2);
PdfPCell cell;
cell = new PdfPCell(new Phrase("My Vertical Text"));
cell.setRotation(90);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell);
htmlWorker.parse(new StringReader(htmlStr));
table.setTotalWidth(400f);
table.writeSelectedRows( 0, -1, 80, 330, writer.getDirectContent()); 

所以方法的魔力writeSelectedRows中放置表到(X,Y)的位置工作。

哪里,

x = 80
y = 330

有关完整细节writeSelectedRows 。

这将有助于面临着同样的问题,有人itext定位。



文章来源: How to add a PdfPTable to the HTML string in a document at (x,y) location using iText?