下面的小例子表示如何使用PDFBox來建立一個新的PDF文檔。java
// 建立一個空的文檔 PDDocument document = new PDDocument(); // 建立一個空的Page而後添加到文檔中 PDPage blankPage = new PDPage(); document.addPage( blankPage ); // 保存文檔 document.save("BlankPage.pdf"); // 必定要確保最後文檔是別關閉的 document.close();
public static void createPDFFile() { PDDocument document = null; PDPage blankPage = null; try { document = new PDDocument(); blankPage = new PDPage(); document.addPage(blankPage); document.save("D:" + File.separator + "pdfBox.pdf"); } catch (COSVisitorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { document.close(); } catch (IOException e) { e.printStackTrace(); } } }
// 建立一個文檔而且添加一個Page PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage( page ); // 建立一個FONTT PDFont font = PDType1Font.HELVETICA_BOLD; // 建立一個待加入的文檔流 PDPageContentStream contentStream = new PDPageContentStream(document, page); // 使用選擇的字體定義一個文本內容 contentStream.beginText(); contentStream.setFont( font, 12 ); contentStream.moveTextPositionByAmount( 100, 700 ); contentStream.drawString( "Hello World" ); contentStream.endText(); // 關閉內容流 contentStream.close(); // 保存結果而且關閉文檔對象 document.save( "Hello World.pdf"); document.close();
public static void usePdfFont() { PDDocument document = new PDDocument(); PDPage page = new PDPage(); PDPageContentStream contentStream = null; PDFont font = PDType1Font.HELVETICA_BOLD; try { document.addPage(page); contentStream = new PDPageContentStream(document, page); contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, 700); contentStream.drawString("Hello World"); contentStream.endText(); } catch (IOException e) { e.printStackTrace(); } finally { try { contentStream.close(); } catch (IOException e) { e.printStackTrace(); } } try { document.save("D:" + File.separator + "Hello World.pdf"); } catch (COSVisitorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { document.close(); } catch (IOException e) { e.printStackTrace(); } } }