首页 > 其他分享 >HTML、图片以及word转换成pdf

HTML、图片以及word转换成pdf

时间:2024-03-27 10:47:20浏览次数:26  
标签:PDF word String import itextpdf HTML new pdf com

一、HTML转PDF

对于Html转换成PDF,首先需要页面前端处理好页面,如果Html不规范或存在 等特殊字符,可能到转换失败。

1.1 Maven引入依赖

        <!-- html转pdf  -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>3.0.2</version>
        </dependency>
        <!-- 中文字体支持 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>font-asian</artifactId>
            <version>7.1.16</version>
        </dependency>

<!--        预处理html-->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.14.3</version>
        </dependency>

1.2 编写工具类

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
import com.itextpdf.styledxmlparser.css.media.MediaDeviceDescription;
import com.itextpdf.styledxmlparser.css.media.MediaType;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class HtmlConvertPdfUtil {

    public static void convertToPdf(String filePath, String pdfPath) throws IOException {
        log.info("{}:进行PDF转换",filePath);
        //对html页面进行预处理
        File input = new File(filePath);
        Document doc = Jsoup.parse(input, "UTF-8");

        // 选择所有的 <script>标签并删除
        Elements scripts = doc.select("script");
        if(!scripts.isEmpty()){
            scripts.remove();
        }

        String processedHtml = doc.outerHtml();
        InputStream inputStream = new ByteArrayInputStream(processedHtml.getBytes());

        //若存在输出的pdf文件先删除,再创建
        File file = new File(pdfPath);
        if(file.isFile() && file.exists()){
            file.delete();
        }

        //创建输出的pdf
        InputStream fileInputStream = new FileInputStream(filePath);
        PdfWriter pdfWriter = new PdfWriter(new FileOutputStream(pdfPath));
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);

        //设置为A4大小
        pdfDocument.setDefaultPageSize(PageSize.A0);

        //添加中文字体支持
        ConverterProperties properties = new ConverterProperties();
        FontProvider fontProvider = new FontProvider();
        fontProvider.addFont("/static/fonts/SimHei.ttf");
        properties.setFontProvider(fontProvider);
        properties.setMediaDeviceDescription(new MediaDeviceDescription(MediaType.PRINT));

        //启用立即刷新和分页控制
        properties.setImmediateFlush(true);

        //读取Html文件流,查找出当中的&nbsp;或出现类似的符号空格字符
        inputStream = readInputStrem(inputStream);
        HtmlConverter.convertToPdf(inputStream, pdfDocument, properties);

        pdfWriter.close();
        pdfDocument.close();
        log.info("{}:PDF转换成功",filePath);
    }

    //从Html文件流查找出当中的&nbsp;或出现类似的符号空格字符并替换掉
    private static InputStream readInputStrem(InputStream inputStream) {
        // 定义一些特殊字符的正则表达式 如:
        String regEx_special = "\\&[a-zA-Z]{1,10};";
        try(ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
            // 创建缓存大小
            byte[] buffer = new byte[108192];
            // 每次读取到内容的长度
            int len = -1;
            // 开始读取输入流中的内容
            while ((len = inputStream.read(buffer)) != -1) { //当等于-1说明没有数据可以读取了
                baos.write(buffer, 0, len);   //把读取到的内容写到输出流中
            }
            // 把字节数组转换为字符串 设置utf-8字符编码
            String content = baos.toString(String.valueOf(StandardCharsets.UTF_8));
            // 关闭输入流和输出流
            inputStream.close();
            // 判断HTML内容是否具有HTML的特殊字符标记
            Pattern compile = Pattern.compile(regEx_special, Pattern.CASE_INSENSITIVE);
            Matcher matcher = compile.matcher(content);
            String replaceAll = matcher.replaceAll("");
            // 将字符串转化为输入流返回
            return getStringStream(replaceAll);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("错误信息:pdf字符串格式化特殊字符失败{}", e.getMessage());
            return null;
        }
    }

    public static InputStream getStringStream(String sInputString) {
        if (sInputString != null && !sInputString.trim().equals("")) {
            try {
                return new ByteArrayInputStream(sInputString.getBytes(StandardCharsets.UTF_8)); // 设置utf-8字符编码
            } catch (Exception e) {
                e.printStackTrace();
                log.error("错误信息:pdf字符串转输入流失败,{}", e.getMessage());
            }
        }
        return null;
    }

}

二、图片转PDF

2.1 Maven引入依赖

<!--        图片转pdf-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>kernel</artifactId>
            <version>7.1.16</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>layout</artifactId>
            <version>7.1.16</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>io</artifactId>
            <version>7.1.16</version>
        </dependency>

2.2 编写工具类

import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.property.HorizontalAlignment;
import lombok.extern.slf4j.Slf4j;


import java.io.File;
import java.io.FileOutputStream;

@Slf4j
public class ImageConvertPdfUtil {

    // 将图片列表转换为 PDF
    public static void convertToPdf(String filePath, String pdfPath) {
        log.info("{}:进行PDF转换",filePath);
        try {
            //若存在该文件先删除,再创建
            File file = new File(pdfPath);
            if(file.isFile() && file.exists()){
                file.delete();
            }

            // 创建 PDF 文档
            PdfWriter writer = new PdfWriter(new FileOutputStream(pdfPath));
            PdfDocument pdfDocument = new PdfDocument(writer);
            Document document = new Document(pdfDocument);

            // 获取pdf页面尺寸
            PageSize pageSize = pdfDocument.getDefaultPageSize();
            float pageWidth = pageSize.getWidth();
            float pageHeight = pageSize.getHeight();

            // 将图片添加到 PDF 文档
            addImageToPdf(document, filePath, pageWidth, pageHeight);

            // 关闭文档
            document.close();
        } catch (Exception e) {
            log.error("convertToPdf-Error:{}",e.getMessage());
        }
        log.info("{}:PDF转换成功",filePath);
    }

    // 将图片添加到 PDF 文档
    private static void addImageToPdf(Document document, String imagePath, float pageWidth, float pageHeight) {
        try {
            // 创建图片对象并设置等比例缩放和水平居中
            Image image = new Image(ImageDataFactory.create(imagePath));
            image.setAutoScale(true);
            image.setHorizontalAlignment(HorizontalAlignment.CENTER);


            // 获取图片的原始尺寸
            float width = image.getImageWidth();
            float height = image.getImageHeight();

            // 计算缩放比例
            float scale = Math.min(pageWidth / width, pageHeight / height);

            // 设置图片的缩放比例
            image.scaleToFit(width * scale, height * scale);

            // 添加图片到 PDF 文档
            document.add(image);

        } catch (Exception e) {
            log.error("addImageToPdf-Error:{}",e.getMessage());
        }
    }
}

三、图片转PDF

3.1 Maven引入依赖

如果下载不成功,去网上搜索下载现有jar包,然后替换版本号

<!--        word转pdf-->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>15.8.0</version>
        </dependency>

3.2 编写工具类

import com.aspose.words.License;
import lombok.extern.slf4j.Slf4j;


import java.io.*;

@Slf4j
public class WordConvertPdfUtil {
    public static void convertDocxToPdf(String filePath, String pdfPath){
        log.info("{}:进行PDF转换",filePath);
		if (!isWordLicense()) {
			return null;
		}
        try {
            //若存在输出的pdf文件先删除,再创建
            File file = new File(pdfPath);
            if(file.isFile() && file.exists()){
                file.delete();
            }
            com.aspose.words.Document document = new com.aspose.words.Document(filePath);
            document.save(pdfPath);
        } catch (Exception e) {
            log.error("convertDocxToPdf-Error:{}",e.getMessage());
        }
        log.info("{}:PDF转换成功",filePath);
    }
	
	/**
	 * @Description: 验证aspose.word组件是否授权:无授权的文件有水印和试用标记
	 */
	public static boolean isWordLicense() {
		boolean result = false;
		try {
		//导入许可
			String licensexml = "<License>\n" + "<Data>\n" + "<Products>\n"
					+ "<Product>Aspose.Total for Java</Product>\n" + "<Product>Aspose.Words for Java</Product>\n"
					+ "</Products>\n" + "<EditionType>Enterprise</EditionType>\n"
					+ "<SubscriptionExpiry>20991231</SubscriptionExpiry>\n"
					+ "<LicenseExpiry>20991231</LicenseExpiry>\n"
					+ "<SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>\n" + "</Data>\n"
					+ "<Signature>\n"
					+ "sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=\n"
					+ "</Signature>\n" + "</License>";
			InputStream inputStream = new ByteArrayInputStream(licensexml.getBytes());
			com.aspose.words.License license = new com.aspose.words.License();
			license.setLicense(inputStream);
			result = true;
		} catch (Exception e) {
			log.error("error:{}",e.getMessage());
		}
		return result;
	}

}

参考资料:https://blog.csdn.net/WayneLee0809/article/details/112788783
https://cloud.tencent.com/developer/article/1639923

标签:PDF,word,String,import,itextpdf,HTML,new,pdf,com
From: https://www.cnblogs.com/Aying216/p/18098381

相关文章

  • Mogdb - 安装报错Failed to encrypt the password for databaseError
    Mogdb-安装报错FailedtoencryptthepasswordfordatabaseError本文出处:https://www.modb.pro/db/418363版本MogdbV2.0.1红旗V6故障现象安装过程中出现报错[GAUSS-50322]:FailedtoencryptthepasswordfordatabaseError:/dbdata/app/mogdb/bin/gs_guc:error......
  • 浏览器工作原理与实践--渲染流程(下):HTML、CSS和JavaScript,是如何变成页面的
    在上篇文章中,我们介绍了渲染流水线中的DOM生成、样式计算和布局三个阶段,那今天我们接着讲解渲染流水线后面的阶段。这里还是先简单回顾下上节前三个阶段的主要内容:在HTML页面内容被提交给渲染引擎之后,渲染引擎首先将HTML解析为浏览器可以理解的DOM;然后根据CSS样式表,计算出DOM......
  • python的应用 | 提取指定文件夹下所有PDF文件的页数
    需求背景:由于要打印几十页pdf,跟打印店对接的时候,为了防止被坑,提前了解一下,所有文档一共有多少页,于是想到了用python来提取pdf文件的页数完整代码:importosfromPyPDF2importPdfReaderdefget_pdf_page_count(folder_path):#初始化总页数变量total_pages=0......
  • 浏览器工作原理与实践--渲染流程(上):HTML、CSS和JavaScript,是如何变成页面的
    在上一篇文章中我们介绍了导航相关的流程,那导航被提交后又会怎么样呢?就进入了渲染阶段。这个阶段很重要,了解其相关流程能让你“看透”页面是如何工作的,有了这些知识,你可以解决一系列相关的问题,比如能熟练使用开发者工具,因为能够理解开发者工具里面大部分项目的含义,能优化页面卡......
  • 深入在线文档系统的 MarkDown/Word/PDF 导出能力设计
    深入在线文档系统的MarkDown/Word/PDF导出能力设计当我们实现在线文档的系统时,通常需要考虑到文档的导出能力,特别是对于私有化部署的复杂ToB产品来说,文档的私有化版本交付能力就显得非常重要,此外成熟的在线文档系统还有很多复杂的场景,都需要我们提供文档导出的能力。那么本文就......
  • Excel表格怎么免费转换pdf?方法汇总分享
    Excel文件是一种非常常见的电子表格文件格式,可以转换成多种样式,那么应该怎么转换成表格呢?下面一起来看看吧!MicrosoftOffice套件(Word、Excel等)如果您使用的是MicrosoftOfficeExcel,只需打开Excel表格,然后点击左上角的“文件”菜单,选择“另存为”(或“SaveAs”),在弹出的保存......
  • word批量添加后缀名的方法有哪些?看这里就够了
    在日常办公和学习中,我们经常需要处理大量的Word文档。有时候,为了更好地组织和管理这些文档,或者为了满足特定的需求,我们可能需要给这些Word文档批量添加后缀。当我们拥有大量的Word文档时,如何有效地分类和管理这些文档成为了一个重要的问题。通过给Word文档批量添加后缀,我们可以......
  • [题解]P5858 Golden Sword
    P5858「SWTR-3」GoldenSword第一道自己想出递推公式并且成功\(AC\)的\(dp\)绿题。题意简述有\(n\)种原料,每个原料有一个耐久度\(a[i]\),必须按照\(1,2,…,n\)的顺序放入炼金锅。但是炼金锅的容量是有限的,只有\(w\),所以在每次放入原料之前,都可以选择取出\(0\sims\)个原料再放......
  • 最详细爬虫零基础教程11——html格式提取之xpath
    文章目录一、html和xml二、xpath获取节点属性三、xpath语法四、案例展示总结一、html和xmllxml是一款高性能的PythonHTML/XML解析器,我们可以利用XPath,来快速的定位特定元素以及获取节点信息。区别:1.xml被设计为传输和存储数据,其焦点是数据的内容2.html是显示......
  • HTML学习笔记5——功能性链接(打电话发邮箱)
    可以跳转至发邮箱打电话等的链接,在vscode中写完代码后右击选择OpenwithliveServer用服务器打开。这篇文章主要介绍发邮箱和用手机打电话。<--都写在body中--><--邮箱格式--><ahref="mailto:[email protected]">邮箱</a><--打电话格式--><ahref="tel:176xxxxxxxx......