2013-12-11 28 views
1

我在做html to pdf conversion使用iText如何在使用iText的(x,y)位置的文檔中的HTML字符串中添加PdfPTable?

我已經使用具有下列內容代碼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}替換[email protected]

所需的輸出:

{VERTICALTEXT}應以90度旋轉的形式替換爲My Vertical Text

+0

我們可以在html文檔中設置表格(x,y)的座標嗎?我添加了'table.writeSelectedRows(40,60,50,80,writer.getDirectContent()); document.add(table);'但是這會在文檔的末尾添加表格,而不是在{VERTICALTEXT}'爲html字符串的確切位置。 –

回答

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定位相同的問題。

相關問題