iText操作pdf(生成,導入圖片等)


生成pdf有很多種方法,用pdfbox也很方便,今天我要寫的是用iText

主要在pom.xml中配置的jar包如下

<dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>4.2.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.eclipse.birt.runtime.3_7_1/com.lowagie.text -->
        <!--<dependency>
            <groupId>org.eclipse.birt.runtime.3_7_1</groupId>
            <artifactId>com.lowagie.text</artifactId>
            <version>2.1.7</version>
        </dependency>
-->
        <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.11</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.lowagie/itext-rtf -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext-rtf</artifactId>
            <version>2.1.7</version>
        </dependency>

如下代碼所示,是生成pdf並且插入文字與圖片

//創建pdf文件,並且寫入文字跟圖片
  public void createPdfWithImg() {
    Document document = null;
    try {
      BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 設置中文字體
      Font headFont = new Font(bfChinese, 10, Font.NORMAL);// 設置字體大小

      document = new Document();
      PdfWriter.getInstance(document, new FileOutputStream("D:/img.pdf"));
      //設定文檔的作者
      document.addAuthor("張小寧"); //測試無效
      document.open();
      document.add(new Paragraph("你好,Img!", headFont));
      //讀取一個圖片
      Image image = Image.getInstance("C:\\Users\\zhxn\\Desktop\\1.jpg");
      //插入一個圖片
      document.add(image);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (document != null) {
        document.close();
      }
    }
  }

其余都不想寫了,項目中也大概就需要這些


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM