63

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.

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

Thanks.

Garth
  • 923
  • 2
  • 10
  • 15

13 Answers13

77

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

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

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.

This is my example from a WinForms app

    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 pdfRenderer control in WinForm: Add the PdfiumViewer NuGet package to the project; open the projects packages folder in Windows Explorer and drag the PdfiumViewer.dll file onto the Toolbox window; A control called PdfRenderer will be available to add:

Adding PdfRenderer control to WinForms

demonplus
  • 5,613
  • 12
  • 49
  • 68
Morphed
  • 3,527
  • 2
  • 29
  • 55
  • 16
    I know this is an old thread, but is worth commenting. If you are working on a close source project and need to deal with pdfs this is the library you want. everything else requires a paid license to use. – ScarletMerlin Oct 15 '15 at 14:14
  • 8
    **This is, by far, the best answer to questions about pdf viewers in winforms apps**. I wonder why it is not marked as an answer to this post! Thanks @Paddy, this was a great help! – aubykhan Jan 31 '16 at 14:39
  • 1
    Note: The current pdfium.dll cannot be loaded into a .NET 4.0 project – CZahrobsky Aug 24 '16 at 18:59
  • Which control is this pdfRenderer? – V K Jan 30 '17 at 13:22
  • 1
    confirming that this still works even in archived state, with packages I got from NuGet (pdfiumViewer & pdfvium native) - in a WPF application (there is an example in the GitHub code, which had me bump into runtime exceptions because of pdfium.dll - but the native NuGet download packages it for you nicely - and the code in the example works) – hello_earth Apr 29 '20 at 12:41
  • confirming that even packaging into single executable the .Net Core way works! this is almost too good to be true – hello_earth Apr 29 '20 at 19:42
  • 5
    For me to get this to work on winforms, I had to install the packages https://www.nuget.org/packages/PdfiumViewer.Native.x86_64.v8-xfa/ and https://www.nuget.org/packages/PdfiumViewer.Native.x86.v8-xfa/ and then copy the /bin/debug/x86 and /bin/debug/x64 folders to the root folder, as per the discussion here: https://github.com/pvginkel/PdfiumViewer/issues/83 – Jack Jun 16 '20 at 00:34
48

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).

For creating the PDF preview, first have a look at some other discussions on the subject on 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, XpdfRasterizer and 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 article that 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 Xpdf as 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 GhostScript as 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 forums as 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.

Community
  • 1
  • 1
Renaud Bompuis
  • 16,596
  • 4
  • 56
  • 86
  • 3
    Poppler option may be easily used from .NET applications when the tool is executed as command line utility with System.Diagnostics.Process - and in this case GPL license is not a blocker for poppler usage in closed-source projects. Recently I've created [C# wrapper for poppler](https://www.nuget.org/packages/NReco.PdfRenderer/) that provides very simple API for PDF rendering. – Vitaliy Fedorchenko Mar 07 '17 at 18:10
13

Here is my answer from a different question.

First you need to reference the Adobe Reader ActiveX Control

Adobe Acrobat Browser Control Type Library 1.0

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

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

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

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

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

otherwise Acrobat might be left lying around.

Omar Shahine
  • 1,935
  • 3
  • 22
  • 30
  • 1
    Just a heads up for anyone else who comes across this - https://github.com/pvginkel/PdfiumViewer is no longer maintained. – Chris Owens Oct 03 '19 at 01:12
  • for those using WPF - unfortunately, while there is a tutorial on how to embed ActiveX controls inside WPF, if you have a 64-bit application, I couldn't make it work because the 32-bit version of the control would always be called, causing System.BadImageFormatException – hello_earth Apr 29 '20 at 11:44
  • replying to the maintenance status of PdfiumViewer - although it's archived, it still works even with a .Net Core 3.1 (WPF) build that I'm working on. and repeating the comments on the other answer - this is the only open-source package out there that uses Apache 2.0 license which is not restrictive like GPL etc. - haven't tried PDFiumSharp though - might be worth a try! – hello_earth Apr 29 '20 at 19:47
11

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

Pages can be rendered to a PDFiumBitmap which 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.

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

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();
            }
        }
    }
}
ArgusMagnus
  • 679
  • 5
  • 14
  • Could you give an example of how to create/use the PDFiumBitmap with a lower color depth? If I set `withTransparency` to false it ends up using BGRx and a 32bit color depth when I want it to use BGR and a 24bit color depth. – Ryan Thomas Aug 30 '19 at 14:16
  • Actually, I was able to find the documentation comments in the underlying pdfium code and figure it out. `var pdfiumBitmap = new PDFiumBitmap((int)scaledWidth, (int)scaledHeight, BitmapFormats.FPDFBitmap_BGR, IntPtr.Zero, 0);` https://cs.chromium.org/chromium/src/third_party/pdfium/public/fpdfview.h?rcl=aea4bca2621bf6c614b9c4c606c4c06e5a968d03&l=910 – Ryan Thomas Aug 30 '19 at 15:47
1

You can add a NuGet package CefSharp.WinForms to your application and then add a ChromiumWebBroweser control to your form. In the code you can write:

chromiumWebBrowser1.Load(filePath);

This is the easiest solution I have found, it is completely free and independent of the user's computer settings like it would be when using default WebBrowser control.

TK-421
  • 294
  • 1
  • 7
  • 26
1

ABCpdf will do this and many other things for you.

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).

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

For more details see:

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.

user81888
  • 27
  • 1
0

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.

Sesh
  • 5,993
  • 4
  • 30
  • 39
  • 4
    I don't see why you would need to use the browser control since it itself uses the Adobe ActiveX plugin that is accessible directly. You just add a layer of complexity and potential issues for apparently no good reason at all. – Renaud Bompuis Feb 07 '11 at 02:18
  • 1
    on the other hand browser control is extremely simple to use and it's ready to go. – aiodintsov Jun 07 '19 at 23:52
0

I would like to mention Docotic.Pdf library here. It can convert PDF to image in C# and VB.NET. And it can also render and print PDF documents.

The library is 100% managed without external dependencies. It does not depend on System.Drawing.dll or GDI+. You will get consistent output on Windows, Linux, macOS, iOS, and Android.

I am one of Docotic.Pdf developers, so I really like it. Please try it and you will probably like it, too.

Bobrovsky
  • 13,789
  • 19
  • 80
  • 130
0

You can also just return a byte[] of a pdf as a file. Here is an example of returning a rendered pdf in a C# web application from a local pdf file. Ideally the pdf would be stored as a byte[] in the database.

public async Task<ActionResult> ViewDocument(GetPdf pdfdata)
{    
    MemoryStream ms = new MemoryStream();
    FileStream stream = new FileStream("Graph.pdf", FileMode.Open, FileAccess.Read);
    stream.CopyTo(ms);

    return File(ms.ToArray(), "application/pdf");
}
micah
  • 838
  • 7
  • 21
-1

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.

http://www.dynamicpdf.com/

Paul Lefebvre
  • 6,253
  • 3
  • 28
  • 36
-1

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

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

This is a great tutorial to get you started.

-2

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

DenNukem
  • 8,014
  • 3
  • 40
  • 45
-4

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

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 out to it. It's not as cool, but it gets the job done for free.

Mark Brackett
  • 84,552
  • 17
  • 108
  • 152