【问题标题】:How to add a PdfPTable to the HTML string in a document at (x,y) location using iText?如何使用 iText 在 (x,y) 位置的文档中将 PdfPTable 添加到 HTML 字符串?
【发布时间】:2013-12-12 20:00:58
【问题描述】:

我正在使用 iTexthtml to pdf conversion

我已经在使用具有以下内容代码的 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 度。

【问题讨论】:

  • 可以在html文档中设置表格(x,y)的坐标吗?我添加了table.writeSelectedRows(40, 60, 50, 80, writer.getDirectContent()); document.add(table);,但这会将表格添加到文档的末尾,而不是{VERTICALTEXT} 在html 字符串中的确切位置。

标签: java android html itext


【解决方案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定位问题的人。

【讨论】:

    猜你喜欢
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    相关资源
    最近更新 更多