How to add a PdfPTable to the HTML string in a doc

2019-08-09 05:09发布

问题:

I am doing html to pdf conversion using iText.

I am already using HTMLWorker class (deprecated) having the following content code:

    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();
}

Now I want to replace {VERTICALTEXT} dynamically with some string.

So I further added the code below:

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));

In the Output:

{VERTICALTEXT} is replaced with com.itextpdf.text.pdf.PdfPTable@41d62bcO

Desired Output:

{VERTICALTEXT} should be replaced with My Vertical Text in a 90 degree rotated form.

回答1:

This is the solution figured out and tested -

Java file relevant code:

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()); 

So the magic of method writeSelectedRows worked in placing the table to the (x, y) location.

Where,

x = 80
y = 330

Complete details about writeSelectedRows.

This will help somebody facing the same problems with itext positioning.