Write PDF File Example
This program demonstrates writing text into a PDF file.
Problem Statement
Write a Java program that creates a PDF file with text using Apache PDFBox.
Source Code
| 1 | import java.io.*; |
| 2 | import org.apache.pdfbox.pdmodel.*; |
| 3 | import org.apache.pdfbox.pdmodel.font.*; |
| 4 | import org.apache.pdfbox.pdmodel.common.*; |
| 5 | public class WritePDFExample { |
| 6 | public static void main(String[] args) { |
| 7 | System.out.println("Eduinq Write PDF Example"); |
| 8 | try(PDDocument doc=new PDDocument()) { |
| 9 | PDPage page=new PDPage(); |
| 10 | doc.addPage(page); |
| 11 | PDPageContentStream cs=new PDPageContentStream(doc,page); |
| 12 | cs.beginText(); |
| 13 | cs.setFont(PDType1Font.HELVETICA_BOLD,12); |
| 14 | cs.newLineAtOffset(100,700); |
| 15 | cs.showText("Eduinq PDF Writing Example"); |
| 16 | cs.endText(); |
| 17 | cs.close(); |
| 18 | doc.save("output.pdf"); |
| 19 | System.out.println("Eduinq PDF Written Successfully"); |
| 20 | } catch(IOException e) { |
| 21 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 22 | } |
| 23 | } |
| 24 | } |
Program Output
Eduinq Write PDF Example Eduinq PDF Written Successfully
Explanation
PDFBox PDPageContentStream writes text into PDF. - Exception handling ensures safe operations. - In enterprise systems, PDF writing is used for reports and invoices. Conclusion: Shows writing PDF files.