使用pdfbox2.0.15版本,将pdf文件转为图片时,中文显示乱码

一、问题

在项目中使用pdfbox2.0.15版本,将pdf文件转成图片,在windows本地转换正常,发布到linux服务器,转换后图片中的中文出现部分乱码,显示都是方块□□□。

二、分析

1、日志查看

后台日志打印出的日志显示,pdf识别出的字体为STSongStd-Light,服务器没有这个字体库,所以按照默认匹配规则,匹配到了UnDotum-Bold这种字体,经查询,UnDotum-Bold主要为韩语字体,无法匹配所有中文字体,所以出现方块□□□。

2019-12-25 14:50:12.308 [http-nio-9281-exec-9] WARN  o.a.p.pdmodel.font.PDCIDFontType0 -Using fallback UnDotum-Bold for CID-keyed font STSongStd-Light
2019-12-25 14:50:12.309 [http-nio-9281-exec-9] WARN  o.a.pdfbox.rendering.CIDType0Glyph2D -No glyph for 27748 (CID 0e13) in font STSongStd-Light

2、瞎折腾

根据网上资料显示,因服务器缺少字体库STSongStd-Light,既然是这样,自然是找到对应的字体库放到服务器上(linux添加字体库教程自行google)。经过一番折腾,字体是有了,但是依旧显示乱码,日志还是显示加载的是UnDotum-Bold,此方法不通只能走其他路子了。

3、源码分析

通过断点调试,在FontMapperImpl类中发现有个substitutes 列表,存放的是字体名称的映射关系,即一种字体不存在时,可以根据这个映射关系,优先匹配对应的字体,部分源码如下:

final class FontMapperImpl implements FontMapper
{
    private static final FontCache fontCache = new FontCache(); // todo: static cache isn't ideal
    private FontProvider fontProvider;
    private Map<String, FontInfo> fontInfoByName;
    private final TrueTypeFont lastResortFont;

    /** Map of PostScript name substitutes, in priority order. */
    private final Map<String, List<String>> substitutes = new HashMap<String, List<String>>();

    FontMapperImpl()
    {
        // substitutes for standard 14 fonts
        substitutes.put("Courier",
                Arrays.asList("CourierNew", "CourierNewPSMT", "LiberationMono", "NimbusMonL-Regu"));
        substitutes.put("Courier-Bold",
                Arrays.asList("CourierNewPS-BoldMT", "CourierNew-Bold", "LiberationMono-Bold",
                        "NimbusMonL-Bold"));
        substitutes.put("Courier-Oblique",
                Arrays.asList("CourierNewPS-ItalicMT","CourierNew-Italic",
                        "LiberationMono-Italic", "NimbusMonL-ReguObli"));
        substitutes.put("Courier-BoldOblique",
                Arrays.asList("CourierNewPS-BoldItalicMT","CourierNew-BoldItalic",
                        "LiberationMono-BoldItalic", "NimbusMonL-BoldObli"));
        substitutes.put("Helvetica",
                Arrays.asList("ArialMT", "Arial", "LiberationSans", "NimbusSanL-Regu"));
        substitutes.put("Helvetica-Bold",
                Arrays.asList("Arial-BoldMT", "Arial-Bold", "LiberationSans-Bold",
                        "NimbusSanL-Bold"));
        substitutes.put("Helvetica-Oblique",
                Arrays.asList("Arial-ItalicMT", "Arial-Italic", "Helvetica-Italic",
                        "LiberationSans-Italic", "NimbusSanL-ReguItal"));
        substitutes.put("Helvetica-BoldOblique",
                Arrays.asList("Arial-BoldItalicMT", "Helvetica-BoldItalic",
                        "LiberationSans-BoldItalic", "NimbusSanL-BoldItal"));
        substitutes.put("Times-Roman",
                Arrays.asList("TimesNewRomanPSMT", "TimesNewRoman", "TimesNewRomanPS",
                        "LiberationSerif", "NimbusRomNo9L-Regu"));
        substitutes.put("Times-Bold",
                Arrays.asList("TimesNewRomanPS-BoldMT", "TimesNewRomanPS-Bold",
                        "TimesNewRoman-Bold", "LiberationSerif-Bold",
                        "NimbusRomNo9L-Medi"));
        substitutes.put("Times-Italic",
                Arrays.asList("TimesNewRomanPS-ItalicMT", "TimesNewRomanPS-Italic",
                        "TimesNewRoman-Italic", "LiberationSerif-Italic",
                        "NimbusRomNo9L-ReguItal"));
        substitutes.put("Times-BoldItalic",
                Arrays.asList("TimesNewRomanPS-BoldItalicMT", "TimesNewRomanPS-BoldItalic",
                        "TimesNewRoman-BoldItalic", "LiberationSerif-BoldItalic",
                        "NimbusRomNo9L-MediItal"));
        substitutes.put("Symbol", Arrays.asList("Symbol", "SymbolMT", "StandardSymL"));
        substitutes.put("ZapfDingbats", Arrays.asList("ZapfDingbatsITC", "Dingbats", "MS-Gothic"));

4、分析结论

因该类没有提供相应的接口设置这个substitutes列表,所以只能通过修改源码来实现。

三、解决

在自己项目中建一个package,路径和FontMapperImpl类所在路径完全一致,并在该包下新建FontMapperImpl类,并将原来的FontMapperImpl类中的代码完全复制过来,在代码中添加一行代码,key为pdf中识别出的字体,value为识别不到时优先匹配的字体,可以匹配多个,排前面则优先匹配:

substitutes.put("STSongStd-Light", Arrays.asList("ArialUnicodeMS","DengXian"));

代码添加后,启动项目,程序会优先加载这个类,经测试,转换后的图片中文显示正常了,问题解决。

============================================================================

四、补充

有网友说上述方案没有效果,原因是服务器中没有没有ArialUnicodeMSDengXian字体,有可能是所有中文字体都没有,在这里提供一个解决方案,不依赖于服务器的字体库,通过在项目中引入字体库文件,需要使用时直接从项目目录中进行加载。

  1. 在项目的resources文件夹中新建ttf文件夹,复制ArialUnicodeMS字体文件到ttf文件夹下。
    在这里插入图片描述
  2. 在自己项目中建一个package,路径和FontMapperImpl类所在路径完全一致,并在该包下新建FontMapperImpl类,并将原来的FontMapperImpl类中的代码完全复制过来。
    在这里插入图片描述
  3. 修改FontMapperImpl文件
    修改1:新增字体匹配规则
substitutes.put("STSongStd-Light", Arrays.asList("ARIALUNI"));

在这里插入图片描述
修改2:替换原有默认加载的字体文件请求路径,改为自己项目中的字体文件路径

 try
    {
        //String ttfName = "/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf";
    	String ttfName = "/ttf/ARIALUNI.TTF";
        InputStream ttfStream = FontMapperImpl.class.getResourceAsStream(ttfName);
        if (ttfStream == null)
        {
            throw new IOException("Error loading resource: " + ttfName);
        }
        TTFParser ttfParser = new TTFParser();
        lastResortFont = ttfParser.parse(ttfStream);
    }
    catch (IOException e)
    {
        throw new RuntimeException(e);
    }

在这里插入图片描述
修改3:注释掉加载系统字体库的代码段
在这里插入图片描述
4. 修改完成后,重新执行转换,发现乱码已经显示正常了。
5. 原理

  • pdfbox首先会加载系统所有的字段库,如果没有加载到系统的字体文件,就会使用pdfbox自带的默认字体文件
  • 由于我们在修改3中已经把加载系统字体文件的代码注释了,所以会使用默认的字体文件。
  • 通过修改2,让pdfbox在加载默认字体文件时,不加载jar包中自带的字体,改成我们项目中自己的字体文件,就可以解决中文乱码的问题了。
  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
你可以使用 Apache PDFBox 库将 HTML 换为 PDF。下面是一个使用 PDFBox 的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.PDPageTree; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.tools.imageio.ImageIOUtil; public class HTMLtoPDFConverter { public static void main(String[] args) { String htmlFilePath = "path/to/input.html"; String pdfFilePath = "path/to/output.pdf"; // Load HTML file File htmlFile = new File(htmlFilePath); try { // Create a new PDF document PDDocument document = new PDDocument(); PDPage page = new PDPage(PDRectangle.A4); document.addPage(page); // Create a PDPageContentStream object PDPageContentStream contentStream = new PDPageContentStream(document, page); // Load the HTML file into a PDStream FileInputStream inputStream = new FileInputStream(htmlFile); PDStream pdStream = new PDStream(document, inputStream); // Set the media box of the page PDRectangle mediaBox = page.getMediaBox(); contentStream.addRect(mediaBox.getLowerLeftX(), mediaBox.getLowerLeftY(), mediaBox.getWidth(), mediaBox.getHeight()); contentStream.clip(); // Create a PDF renderer PDFRenderer renderer = new PDFRenderer(document); renderer.setDocument(document); // Render the HTML file to PDF renderer.renderPageToStream(renderer.getCurrentPageNo(), pdStream); // Close the content stream and the document contentStream.close(); document.save(new FileOutputStream(pdfFilePath)); document.close(); System.out.println("HTML converted to PDF successfully."); } catch (IOException e) { e.printStackTrace(); } } } ``` 请确保将 `path/to/input.html` 替换为要换的 HTML 文件的路径,将 `path/to/output.pdf` 替换为保存生成的 PDF 文件的路径。运行此代码将生成一个包含 HTML 内容的 PDF 文件
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值