如果没有现有文件,如何创建一个全新的 PDF 文件?

How to create a completely new PDF file if there is NO existing file?

我正在使用 iText 库在 java 中创建 PDF 文件。唯一的问题是:我必须首先手动创建一个 PDF 文件,然后获取它的路径并像这样放置它:

private final static String FILE = "C:\Projekt\lul.pdf";
PdfWriter.getInstance(document, new FileOutputStream(FILE));

我的问题是:如何在不手动创建 PDF 文件的情况下使用 iText 库?

private final static String FILE = "C:\Projekt\lul.pdf";
File yourFile = new File(FILE);
yourFile.createNewFile(); // if file already exists will do nothing 
PdfWriter.getInstance(document, new FileOutputStream(yourFile));

iText is an open source API and it does let you do that as well.

  1. 将以下依赖项添加到 pom.xml :

     <dependency>
         <groupId>com.itextpdf</groupId>
         <artifactId>itextpdf</artifactId>
     </dependency>
    
  2. Java Class:

      Document document = new Document();
      PdfWriter writer = PdfWriter.getInstance(document, new 
      FileOutputStream(Example.pdf;));
      document.open();
      document.add(new Paragraph(Welcome To Whosebug;));
      document.close();
      writer.close();