aspose做word转pdf及加水印,Mac/Linux/docker环境乱码问题解决

java 使用aspose做word转pdf

代码如下


import com.aspose.words.Shape;
import com.aspose.words.*;

import java.awt.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * word转Pdf工具
 *
 * @author lshuhao
 * @version 1.0
 * @date 2021/3/9 上午11:59
 */
public class WordUtil {

    /***
     * args[0] 输入文件绝对路径
     * args[1] 输出文件绝对路径
     * args[2] 水印文字
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        File file1 = new File(args[0]);
        if (!file1.exists()) {
            System.out.println("文件:" + args[0] + "不存在");
        }
        FileChannel channel;
        FileInputStream fs;
        byte[] fileByte = null;
        try {
            fs = new FileInputStream(file1);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while (channel.read(byteBuffer) > 0) {
                System.out.println("文件读取完毕");
            }
            fileByte = byteBuffer.array();
        } catch (Exception e) {
            System.err.println("文件读取异常:" + e.getMessage());
        }
        FileOutputStream fos = new FileOutputStream(new File(args[1]));
        byte[] pdf = word2Pdf(fileByte, args[2]);
        if (pdf == null) {
            return;
        }
        fos.write(pdf, 0, pdf.length);
        fos.flush();
        fos.close();
        System.out.println("Word " + args[0] + " 文件转换成功 :" + args[1]);
    }

    /***
     * word转pdf
     *
     * @param word
     * @param watermarkText
     * @return
     */
    public static byte[] word2Pdf(byte[] word, String watermarkText) {
        ByteArrayInputStream in = new ByteArrayInputStream(word);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            getLicense();
            Document doc = new Document(in);
            // 保存转换的pdf文件
            WordUtil.insertWatermarkText(doc, watermarkText == null ? "我的水印" : watermarkText);
            doc.save(out, SaveFormat.PDF);
            return out.toByteArray();
        } catch (Exception e) {
            System.err.println("合同文件转换错误" + e.getMessage());
            return null;
        } finally {
            try {
                if (out != null) {
                    in.close();
                    out.close();
                }
            } catch (IOException e) {
                System.err.println("合同文件转换错误" + e.getMessage());
            }
        }
    }

    private static void getLicense() {
        try {
            // 凭证
            String licenseStr = "<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>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                    "  </Data>\n" +
                    "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                    "</License>";
            InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));
            License asposeLic = new License();
            asposeLic.setLicense(license);
        } catch (Exception e) {
        }
    }

    /**
     * PDF生成水印
     *
     * @param doc           需要添加的pdf文档
     * @param watermarkText 水印内容
     * @throws Exception
     */
    private static void insertWatermarkText(Document doc, String watermarkText) throws Exception {
        Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
        //水印内容
        watermark.getTextPath().setText(watermarkText);
        //水印字体
        watermark.getTextPath().setFontFamily("宋体");
        //水印宽度
        watermark.setWidth(500);
        //水印高度
        watermark.setHeight(100);
        //旋转水印
        watermark.setRotation(-40);
        //水印颜色
        watermark.getFill().setColor(Color.lightGray);
        watermark.setStrokeColor(Color.lightGray);

        watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
        watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
        watermark.setWrapType(WrapType.NONE);
        watermark.setVerticalAlignment(VerticalAlignment.CENTER);
        watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);

        Paragraph watermarkPara = new Paragraph(doc);
        watermarkPara.appendChild(watermark);

        for (Section sect : doc.getSections()) {
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST);
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN);
        }
    }

    private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) throws Exception {
        HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);
        if (header == null) {
            header = new HeaderFooter(sect.getDocument(), headerType);
            sect.getHeadersFooters().add(header);
        }
        header.appendChild(watermarkPara.deepClone(true));
    }

}

上述代码各处可见,最麻烦的问题在于,当我们在本地 Windows 环境测试没有问题,上到测试或者生产的linux、docker服务器时就会出现乱码

原因在于MacOs/linux系统字体库没有对应office的各种中文字体

解决方法

首选拿到 window 安装了office的字体库

1.linux环境下
#上传本地字体库
scp /Users/Desktop/Fonts.zip -i sum root@192.168.1.100:/ 

#进入服务器192.168.1.100  [这里是举例服务器]

ssh root@192.168.1.100
#解压到系统字体库目录
unzip -o -d /usr/share/fonts/ Fonts.zip
#如果unzip未安装,则运行 yum install unzip 

#刷新字体库缓存
fc-cache -fv 
# 重启服务器字体库起效,不重启也有可能起效,保险起见还是重启
shutdown -r now

fc-list :lang=zh 使用这个命令可以看到如下数据就说明成功了
UTOOLS1579401749656.png
重启项目使用就不乱码了

2.docker环境下

重复上面操作,不过进入的服务器是宿主机

docker run **-v /usr/share/fonts:/usr/share/fonts**   ***
docker启动时共享宿主机的字体库重启docker项目即可解决乱码问题
3.MacOs 系统环境下

打开字体册app

找到系统字体库,把 window 的字体库安装进系统
用户 ->> 文件->添加字体
在这里插入图片描述
选择所有从 windows 获取的 Fonts字体库 添加即可
会有部分添加失败,不过也不重要,也够转 PDF 使用了

最后注意

 
String[] fontsPath = new String[]{"/System/Library/Fonts/", "/Users/lgoodbook/Fonts/", "/usr/share/fonts/Fonts/"};
// 这一段代码指定了字体库位置

Font.zip下载地址

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值