PDF转换工具类(byte[]转PDF并生成文件)

这个博客介绍了如何将HTML内容转换成标准的XHTML,然后使用iText库将XHTML转换为PDF文件。过程中涉及的关键技术包括Tidy库进行HTML清理,iText库创建PDF,以及自定义字体提供者。最终,代码示例展示了如何将生成的PDF内容写入到文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PDF转换工具类(byte[]转PDF并生成文件)

对html转为标准的xhtml

  public byte[] transferHtml2XHtml(byte[] html)
  {
    Tidy tidy = new Tidy();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    tidy.setQuiet(true);
    tidy.setInputEncoding("utf-8");
    tidy.setQuiet(true);
    tidy.setOutputEncoding("utf-8");
    tidy.setShowWarnings(false);
    tidy.setIndentContent(true);
    tidy.setSmartIndent(true);
    tidy.setIndentAttributes(false);
    tidy.setWraplen(1024);
    tidy.setXHTML(true);
    tidy.parseDOM(new ByteArrayInputStream(html), baos);
    return baos.toByteArray();
  }

将标准的byte[]转为PDF

  /**
     * @param xhtml xhtml文件内容
     * @return 转换后的pdf文件内容
     * @throws Exception
     */
    public static byte[] transferPDF2Html(byte[] xhtml) throws Exception {
        ByteArrayOutputStream pdfOS = new ByteArrayOutputStream();
        System.out.println(pdfOS);
        Document document = new Document(PageSize.A4, 36, 36, 36, 36);// 上、下、左、右间距
        PdfWriter writer = PdfWriter.getInstance(document, pdfOS);
        document.open();
        InputStream is = new ByteArrayInputStream(xhtml);
        System.out.println("is    :"+is);
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is, StandardCharsets.UTF_8, new FontProvider() {
            public boolean isRegistered(String fontname) {
                return false;
            }
            public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color) {
                try {
                    BaseFont bfChinese;
//                    bfChinese = BaseFont.createFont("STSong-Light", "Adobe-GB1-0", BaseFont.NOT_EMBEDDED);
//                    bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UTF8-H", BaseFont.NOT_EMBEDDED);
                    bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                    return new Font(bfChinese, size, style, color);
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
        document.close();
        byte[] pdfByte = pdfOS.toByteArray();
        pdfOS.close();
        is.close();
        writer.close();
        log.info("PDF转换完成");
        return pdfByte;
    }

生成pdf文件

public static void getFile(byte[] bfile, String filePath, String fileName)
  {
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    File file = null;
    try
    {
      File dir = new File(filePath);
      if ((!dir.exists()) && (dir.isDirectory())) {
        dir.mkdirs();
      }
      file = new File(filePath + "\\" + fileName);
      fos = new FileOutputStream(file);
      bos = new BufferedOutputStream(fos);
      bos.write(bfile); return;
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      if (bos != null) {
        try
        {
          bos.close();
        }
        catch (IOException e1)
        {
          e1.printStackTrace();
        }
      }
      if (fos != null) {
        try
        {
          fos.close();
        }
        catch (IOException e1)
        {
          e1.printStackTrace();
        }
      }
    }
  }

相关jar包

<!--jsoup start -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.7.3</version>
        </dependency>
        <dependency>
            <groupId>net.sf.jtidy</groupId>
            <artifactId>jtidy</artifactId>
            <version>r938</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.2</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.13.2</version>
        </dependency>
<!--jsoup end -->
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值