亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 java Apache PDFBOX 添加 HTML 標記

使用 java Apache PDFBOX 添加 HTML 標記

三國紛爭 2023-09-20 16:34:04
我一直在使用 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'


查看完整回答
反對 回復 2023-09-20
?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

PDFBox 不支持 HTML,至少不支持創建內容。

因此,使用普通 PDFBox,您必須自己解析 HTML 并從文本所在的標簽中派生特殊的文本繪制特征。

例如,當您遇到時"<h1>HelloWorld</h1>",您必須提取文本"HelloWorld"并使用標簽中的信息h1來選擇適當的主要標題字體和字體大小來繪制該文本"HelloWorld"

或者,您可以尋找一個為 PDFBox 執行 HTML 解析和轉換為 PDF 文本繪制指令的庫,例如Open HTML to PDF。


查看完整回答
反對 回復 2023-09-20
  • 2 回答
  • 0 關注
  • 133 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號