Unity中PDF文件转图片

发表于2018-07-08
评论0 4.7k浏览
记录下最近做的在Unity中通过转换Pdf文件为图片的方式以显示文档的方法,供以后参考。
网上相关的插件不算多,也不算少,我采用的是Github上的PdfiumViewer插件,因为该插件是在C#基础上对pdf文档做显示、放大等常规操作,而我只需要在Unity中显示就行,所以去除了其中大部分功能,因能力问题,去除方式有些粗糙。如有需要,可在这里下载。

准备
导入pdfium.dll,PdfiumViewerForUnity.dll到Assets/Plugins/x64目录下,注意二者需在同一目录下;

因为我是采用插件生成Bitmap再转换为Sprite的方式,所以还需导入System.Drawing.dll文件;
PlayerSetting中的API Compatibility Level设置为”.NET 2.0”;

遇到的问题

因技术和人品问题,我比较“擅长”踩坑,这里记录下以供参考:
1.最开始测试的时候,编辑器中运行一次,正常得到结果,再运行就会报错”dll not found”,需要将PdfiumViewerForUnity.dll拖出目录运行一次,再拖回去,就正常了,原因不明;

2.pdfium.dll需要复制到程序或工程的根目录下,否则无法正常使用,我在使用中同时保留了Plugins/x64中原本,至于是否仅放在根目录下即可,有兴趣可自行测试;

3.API Compatibility Level设置为”.NET 2.0 Subset”,无法正常使用;

4.我是将转换的图片再转成Texture2D,然后赋值为UGUI的Image组件,这种方式会出现需要手动调节下Image的Color值或者禁用Image再启用等方式(应该就是重新渲染)才可正常显示图片的问题,如果使用Sprite,则正常,原因不明;

主要步骤

一、参考PdfiumViewer工程,使用NuGet的方式获取pdfium.dll文件(对应命令为:Install-Package PdfiumViewer -Version 2.12.0,参考这里),编写自己的PdfiumViewerForUnity类库,因为只是用于测试转换图片的主要功能,加上技术水平较低,所以方式比较粗暴,如有下载的朋友,可自行美化一番;

二、将PdfiumViewerForUnity.dll导入pdfium同目录下,Unity中配置好相关组件后编写代码。

三、代码如下:
using UnityEngine;
using PdfiumViewerForUnity;
using UnityEngine.UI;
using System.IO;
public class PDFManager : MonoBehaviour {
    public UnityEngine.UI.Image img_Show;
    public int pageIndex;
    void Awake () {
        PrepareDll();
    }
    public void OpenPDF(string filePath)
    {
        //实例化类,并加载本地pdf文件,filePath即文件路径
        PdfViewer pdfViewer = new PdfViewer();
        pdfViewer.Document = PdfDocument.Load(filePath);
oad(filePath);
        //转换为Bitmap
        System.Drawing.Bitmap img = pdfViewer.Document.Render(pageIndex, 1024, 1024, PdfRenderFlags.ForPrinting);
        //转换为流,再获取byte[],这里我试过img.LockBits的方式,不行
        MemoryStream stream = new MemoryStream();
        img.Save(stream,System.Drawing.Imaging.ImageFormat.Bmp);
        byte[] buffer = stream.GetBuffer();
        stream.Close();
        //转换成Texture2D
        Texture2D tex = new Texture2D(1024, 1024, TextureFormat.ARGB32, false);
        tex.LoadRawTextureData(buffer);
        tex.Apply();
        //转换成Sprite
        Sprite sp = Sprite.Create(tex,new Rect(0,0,tex.width,tex.height),Vector2.zero);
        //img_Show.material.mainTexture = tex;
        img_Show.sprite = sp;
    }
    private void PrepareDll()
    {
        //检查pdfium.dll是否在程序根目录下
        string destPath = Path.GetDirectoryName(Application.dataPath) + "/pdfium.dll";
        if (File.Exists(destPath))
        {
            return;
        }
        string pluginPath = Application.dataPath;
#if UNITY_EDITOR
        pluginPath += "/Plugins/x64/pdfium.dll";
#elif UNITY_STANDALONE_WIN
        pluginPath += "/Plugins/pdfium.dll";
#endif
        if (File.Exists(pluginPath)
        {
            File.Copy(pluginPath, destPath);
        }
    }
}

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引