?Java輸入字符串生成PDF文件過程:
? ? ? ? 在Java開發中,如何將字符串轉換為 PDF 是一個常見的需求。網上找了很多例子都無法生成,經過多次嘗試,終于實現了,特此記錄一下。
1、引入pom.xml 添加所需的依賴
<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.5</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>
2、代碼實現
public static void main(String[] args) {Document document = new Document();try {// 設置輸出路徑和文件名PdfWriter.getInstance(document, new FileOutputStream("輸出的PDF文件地址"));document.open();// 設置中文字體BaseFont baseFont = null;try {baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);} catch (IOException e) {throw new RuntimeException(e);}// 添加標題Paragraph title = new Paragraph("標題內容", new Font(baseFont, 16, Font.BOLD));// 設置標題居中title.setAlignment(Paragraph.ALIGN_CENTER);document.add(title);// 添加內容String content = "正文內容";// 設置正文的格式Font font = new Font(baseFont, 13, Font.BOLD);Paragraph paragraph = new Paragraph(content, font);document.add(paragraph);} catch (DocumentException | IOException e) {e.printStackTrace();}finally {document.close();}}
3、結論
??通過以上代碼可以正常生成PDF文件,更多內容其他格式,請自行設置。