如何使用 C# 渲染 pdf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/518878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:31:07  来源:igfitidea点击:

How to render pdfs using C#

c#pdfdrawingrendering

提问by Garth

I want to load and draw pdf files graphically using C#. I don't need to edit them or anything, just render them at a given zoom level.

我想使用 C# 以图形方式加载和绘制 pdf 文件。我不需要编辑它们或任何东西,只需在给定的缩放级别渲染它们。

The pdf libraries I have found seem to be focussed on generation. How do I do this?

我发现的 pdf 库似乎专注于生成。我该怎么做呢?

Thanks.

谢谢。

采纳答案by Renaud Bompuis

There are a few other choices in case the Adobe ActiveX isn't what you're looking for (since Acrobat must be present on the user machine and you can't ship it yourself).

如果 Adob​​e ActiveX 不是您要找的东西,还有其他一些选择(因为 Acrobat 必须存在于用户机器上,而且您不能自己发送)。

For creating the PDF preview, first have a look at some other discussions on the subject on StackOverflow:

要创建 PDF 预览,请先查看 StackOverflow 上有关该主题的其他一些讨论:

In the last two I talk about a few things you can try:

在最后两个中,我谈到了一些你可以尝试的事情:

  • You can get a commercial renderer (PDFViewForNet, PDFRasterizer.NET, ABCPDF, ActivePDF, XpdfRasterizerand others in the other answers...).
    Most are fairly expensive though, especially if all you care about is making a simple preview/thumbnails.

  • In addition to Omar Shahine's code snippet, there is a CodeProject articlethat shows how to use the Adobe ActiveX, but it may be out of date, easily broken by new releases and its legality is murky (basically it's ok for internal use but you can't ship it and you can't use it on a server to produce images of PDF).

  • You could have a look at the source code for SumatraPDF, an OpenSource PDF viewer for windows.

  • There is also Poppler, a rendering engine that uses Xpdfas a rendering engine. All of these are great but they will require a fair amount of commitment to make make them work and interface with .Net and they tend to be be distributed under the GPL.

  • You may want to consider using GhostScriptas an interpreter because rendering pages is a fairly simple process.
    The drawback is that you will need to either re-package it to install it with your app, or make it a pre-requisite (or at least a part of your install process).
    It's not a big challenge, and it's certainly easier than having to massage the other rendering engines into cooperating with .Net.
    I did a small project that you will find on the Developer Express forumsas an attachment.
    Be careful of the license requirements for GhostScript through.
    If you can't leave with that then commercial software is probably your only choice.

  • 您可以获得商业渲染器(PDFViewForNetPDFRasterizer.NETABCPDFActivePDFXpdfRasterizer和其他答案中的其他人......)。
    不过,大多数都相当昂贵,特别是如果您只关心制作简单的预览/缩略图。

  • 除了 Omar Shahine 的代码片段之外,还有一篇CodeProject 文章展示了如何使用 Adob​​e ActiveX,但它可能已经过时,很容易被新版本破坏,并且其合法性是模糊的(基本上内部使用是可以的,但你可以不发货,也不能在服务器上使用它来生成 PDF 图像)。

  • 您可以查看SumatraPDF的源代码,是一个适用于 Windows 的开源 PDF 查看器。

  • 还有Poppler,一个使用Xpdf作为渲染引擎的渲染引擎。所有这些都很棒,但它们需要相当多的承诺才能使它们工作并与 .Net 接口,并且它们往往在 GPL 下分发。

  • 您可能需要考虑使用GhostScript作为解释器,因为渲染页面是一个相当简单的过程。
    缺点是您需要重新打包它以与您的应用程序一起安装,或者使其成为先决条件(或至少是安装过程的一部分)。
    这不是一个很大的挑战,而且肯定比让其他渲染引擎与 .Net 合作更容易。
    我做了一个小项目,您可以在Developer Express 论坛上找到它作为附件。
    请注意 GhostScript through 的许可要求。
    如果你不能离开,那么商业软件可能是你唯一的选择。

回答by Paul Lefebvre

Dynamic PDF Viewer from ceTe software might do what you're looking for. I've used their generator software and was pretty happy with it.

ceTe 软件的动态 PDF 查看器可能会满足您的需求。我使用过他们的生成器软件并且对它非常满意。

http://www.dynamicpdf.com/

http://www.dynamicpdf.com/

回答by Sesh

Use the web browser control. This requires Adobe reader to be installed but most likely you have it anyway. Set the UrL of the control to the file location.

使用网络浏览器控件。这需要安装 Adob​​e reader,但很可能你已经安装了它。将控件的 UrL 设置为文件位置。

回答by Mark Brackett

You could google for PDF viewer component, and come up with more than a few hits.

您可以在 google 上搜索PDF 查看器组件,并找到一些点击次数。

If you don't really need to embed them in your app, though - you can just require Acrobat Reader or FoxIt (or bundle it, if it meets their respective licensing terms) and shell outto it. It's not as cool, but it gets the job done for free.

如果你不是真的需要在你的应用程序中嵌入他们这样做,虽然-你可以只需要Acrobat Reader或福昕(或捆绑它,如果它符合各自的许可条款),并掏出它。它不是那么酷,但它可以免费完成工作。

回答by Mark Brackett

The easiest lib I have used is Paolo Gios'slibrary. It's basically

我使用过的最简单库是Paolo Gios 的库。基本上是

Create GiosPDFDocument object
Create TextArea object
Add text, images, etc to TextArea object
Add TextArea object to PDFDocument object
Write to stream

Thisis a great tutorial to get you started.

是一个很好的教程,可以帮助您入门。

回答by Omar Shahine

Here is my answer from a different question.

这是我从另一个问题中得到的答案。

First you need to reference the Adobe Reader ActiveX Control

首先你需要参考Adobe Reader ActiveX Control

Adobe Acrobat Browser Control Type Library 1.0

Adobe Acrobat 浏览器控件类型库 1.0

%programfiles&\Common Files\Adobe\Acrobat\ActiveX\AcroPDF.dll

%programfiles&\Common Files\Adobe\Acrobat\ActiveX\AcroPDF.dll

Then you just drag it into your Windows Form from the Toolbox.

然后您只需将它从工具箱拖到您的 Windows 窗体中。

And use some code like this to initialize the ActiveX Control.

并使用一些这样的代码来初始化 ActiveX 控件。

private void InitializeAdobe(string filePath)
{
    try
    {
        this.axAcroPDF1.LoadFile(filePath);
        this.axAcroPDF1.src = filePath;
        this.axAcroPDF1.setShowToolbar(false);
        this.axAcroPDF1.setView("FitH");
        this.axAcroPDF1.setLayoutMode("SinglePage");
        this.axAcroPDF1.Show();
    }
    catch (Exception ex)
    {
        throw;
    }
}

Make sure when your Form closes that you dispose of the ActiveX Control

确保在您的表单关闭时处理 ActiveX 控件

this.axAcroPDF1.Dispose();
this.axAcroPDF1 = null;

otherwise Acrobat might be left lying around.

否则可能会留下 Acrobat。

回答by user81888

ABCpdf will do this and many other things for you.

ABCpdf 会为你做这件事和许多其他事情。

Not ony will it render your PDF to a variety of formats (eg JPEG, GIF, PNG, TIFF, JPEG 2000; vector EPS, SVG, Flash and PostScript) but it can also do so in a variety of color spaces (eg Gray, RGB, CMYK) and bit depths (eg 1, 8, 16 bits per component).

它不仅可以将您的 PDF 呈现为各种格式(例如 JPEG、GIF、PNG、TIFF、JPEG 2000;矢量 EPS、SVG、Flash 和 PostScript),而且还可以在各种颜色空间(例如灰色、 RGB、CMYK)和位深度(例如每个组件 1、8、16 位)。

And that's just some of what it will do!

这只是它会做的一些事情!

For more details see:

有关更多详细信息,请参阅:

http://www.websupergoo.com/abcpdf-8.htm

http://www.websupergoo.com/abcpdf-8.htm

Oh and you can get free licenses via the free license scheme.

哦,您可以通过免费许可计划获得免费许可。

There are EULA issues with using Acrobat to do PDF rendering. If you want to go down this route check the legalities very carefully first.

使用 Acrobat 进行 PDF 渲染存在 EULA 问题。如果你想沿着这条路走下去,首先要非常仔细地检查合法性。

回答by DenNukem

This looks like the right thing: http://code.google.com/p/lib-pdf/

这看起来是正确的:http: //code.google.com/p/lib-pdf/

回答by Paddy

Google has open sourced its excellent PDF rendering engine - PDFium- that it wrote with Foxit Software.

谷歌已经开源了它使用福昕软件编写的出色的 PDF 渲染引擎——PDFium

There is a C# nuget package called PdfiumViewerwhich gives a C# wrapper around PDFium and allows PDFs to be displayed and printed.

有一个名为PdfiumViewer的 C# nuget 包,它为PDFium提供了一个 C# 包装器,并允许显示和打印 PDF。

I have used it and was very impressed with the quality of the rendering.

我已经使用过它并且对渲染的质量印象非常深刻。



PDFium works directly with streams so it doesn't require any data to be written to disk.

PDFium 直接处理流,因此不需要将任何数据写入磁盘。

This is my example from a WinForms app

这是我在 WinForms 应用程序中的示例

    public void LoadPdf(byte[] pdfBytes)
    {
        var stream = new MemoryStream(pdfBytes);
        LoadPdf(stream)
    }

    public void LoadPdf(Stream stream)
    {
        // Create PDF Document
        var pdfDocument = PdfDocument.Load(stream);

        // Load PDF Document into WinForms Control
        pdfRenderer.Load(pdfDocument);
    }


Edit: To get the pdfRenderercontrol in WinForm: Add the PdfiumViewerNuGet package to the project; open the projects packages folder in Windows Explorer and drag the PdfiumViewer.dllfile onto the Toolboxwindow; A control called PdfRendererwill be available to add:

编辑:在WinForm中获取pdfRenderer控件:将PdfiumViewerNuGet包添加到项目中;在 Windows 资源管理器中打开项目包文件夹并将PdfiumViewer.dll文件拖到Toolbox窗口上;一个名为的控件PdfRenderer将可用于添加:

Adding PdfRenderer control to WinForms

将 PdfRenderer 控件添加到 WinForms

回答by ArgusMagnus

PdfiumViewer is great, but relatively tightly coupled to System.Drawingand WinForms. For this reason I created my own wrapper around PDFium: PDFiumSharp

PdfiumViewer 很棒,但System.Drawing与 WinForms耦合相对紧密。出于这个原因,我围绕 PDFium 创建了自己的包装器:PDFiumSharp

Pages can be rendered to a PDFiumBitmapwhich in turn can be saved to disk or exposed as a stream. This way any framework capable of loading an image in BMP format from a stream can use this library to display pdf pages.

页面可以呈现为PDFiumBitmap,后者又可以保存到磁盘或作为流公开。这样,任何能够从流中加载 BMP 格式图像的框架都可以使用这个库来显示 pdf 页面。

For example in a WPF application you could use the following method to render a pdf page:

例如,在 WPF 应用程序中,您可以使用以下方法呈现 pdf 页面:

using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using PDFiumSharp;

static class PdfRenderer
{
    public static ImageSource RenderPage(string filename, int pageIndex, string password = null, bool withTransparency = true)
    {
        using (var doc = new PdfDocument(filename, password))
        {
            var page = doc.Pages[pageIndex];
            using (var bitmap = new PDFiumBitmap((int)page.Width, (int)page.Height, withTransparency))
            {
                page.Render(bitmap);
                return new BmpBitmapDecoder(bitmap.AsBmpStream(), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
            }
        }
    }
}