我一直在使用 PDFBOX 和 EasyTable,它擴展了 PDFBOX 來繪制數據表。我遇到了一個問題,我有一個帶有 HTML 數據字符串的 java 對象,我需要使用 PDFBOX 將其添加到 PDF 中。對文檔的挖掘似乎沒有產生任何成果。下面的代碼是一個片段 hello world,我希望生成的 pdf 具有 H1 格式。// Create a document and add a page to it PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage( page );// Create a new font object selecting one of the PDF base fonts PDFont font = PDType1Font.HELVETICA_BOLD;// Start a new content stream which will "hold" the to be created content PDPageContentStream contentStream = new PDPageContentStream(document, page);// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World" contentStream.beginText(); contentStream.setFont( font, 12 ); contentStream.moveTextPositionByAmount( 100, 700 ); contentStream.drawString( "<h1>HelloWorld</h1>" ); contentStream.endText();// Make sure that the content stream is closed: contentStream.close();// Save the results and ensure that the document is properly closed: document.save( "Hello World.pdf"); document.close(); }
2 回答

慕娘9325324
TA貢獻1783條經驗 獲得超4個贊
使用jerico將 html 格式化為自由文本,同時正確映射標簽的輸出。
樣本
public?String?extractAllText(String?htmlText){ ????return?new?net.htmlparser.jericho ????????????.Source(htmlText) ????????????.getRenderer() ????????????.setMaxLineLength(Integer.MAX_VALUE) ????????????.setNewLine(null) ????????????.toString(); }
在你的 gradle 或 Maven 中包含:
compile?group:?'net.htmlparser.jericho',?name:?'jericho-html',?version:?'3.4'

繁花不似錦
TA貢獻1851條經驗 獲得超4個贊
PDFBox 不支持 HTML,至少不支持創建內容。
因此,使用普通 PDFBox,您必須自己解析 HTML 并從文本所在的標簽中派生特殊的文本繪制特征。
例如,當您遇到時"<h1>HelloWorld</h1>"
,您必須提取文本"HelloWorld"
并使用標簽中的信息h1
來選擇適當的主要標題字體和字體大小來繪制該文本"HelloWorld"
。
或者,您可以尋找一個為 PDFBox 執行 HTML 解析和轉換為 PDF 文本繪制指令的庫,例如Open HTML to PDF。
添加回答
舉報
0/150
提交
取消