如何使用 Ghostscript 将 pdf 转换为内存流中的图像?

问题描述 投票:0回答:1

我使用 GhostscriptWrapper 将 pdf 转换为图像
但如何将 pdf 转换为内存流中的图像而不是保存它
我需要设计 pdf 查看器,并且需要将 pdf 转换为内存流中的图像

        GhostscriptSettings gs = new GhostscriptSettings();
        gs.Device = GhostscriptDevices.png16m;
        gs.Page = new GhostscriptPages { Start = page, End = page };
        gs.Resolution = new Size { Height = 150, Width = 150 };
        gs.Size = new GhostscriptPageSize { Native = GhostscriptPageSizes.a4 };
        GhostscriptWrapper.GenerateOutput("C:\\PDFViewer\\my\\test.pdf", "C:\\PDFViewer\\my\\test.png", gs);
c# asp.net ghostscript ghostscript.net
1个回答
0
投票

GhostScript.net 支持内存流(非物理文件)。

但是,我不确定您是否可以实时执行此操作,因为将 PDF 转换为图像需要大量的 CPU 和处理,而且这是一个较大的 PDF。

但是,假设有一个 PDF 文件,然后我们希望将 PDF(第一页)显示为图像,并且无需在磁盘上创建图像文件。

所以,我们有这个标记:

        <asp:Button ID="Button1" runat="server" Text="Get PDF Image" 
            CssClass="btn"
            OnClick="Button1_Click"                
            />
        <br />
        <br />

        <asp:Image ID="Image1" runat="server" Height="215px" Width="334px" />

因此,网页上有一个简单的按钮和图像。

因此,对于给定的 pdf 文件,让我们显示缩略图(图像),并且在不创建文件(内存流)的情况下执行此操作。

所以,背后的代码是这样的:

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        string strF = @"c:\test\CONTROL.pdf";

        byte[] MyBytePic = GetPdfThumb(strF);

        string sMineType = MimeMapping.GetMimeMapping("abc.jpeg");

        Image1.ImageUrl =
                $@"data:{sMineType};base64,{Convert.ToBase64String(MyBytePic)}";


    }

    public byte[] GetPdfThumb(string strPDF)
    {
        Ghostscript.NET.GhostscriptVersionInfo gVER;
        string strgDLL = System.Web.HttpContext.Current.Server.MapPath(@"~\MyDLL") + @"\gsdll64.dll";
        gVER = new Ghostscript.NET.GhostscriptVersionInfo(new Version(0, 0, 0), 
                    strgDLL, "", Ghostscript.NET.GhostscriptLicense.GPL);

        using (GhostscriptRasterizer gPDF = new GhostscriptRasterizer())
        {
            using (MemoryStream fs = new MemoryStream())
            {
                try
                {
                    gPDF.Open(strPDF, gVER, true);
                    gPDF.GetPage(18, 1).Save(fs, ImageFormat.Jpeg);
                    gPDF.Close();
                    fs.Close();

                    return fs.ToArray();
                }
                catch (Exception ex)
                {
                    Debug.Print(ex.Message);
                    return new byte[0];
                }
            }
        }
    }

结果是这样的:

© www.soinside.com 2019 - 2024. All rights reserved.