Open a PDF in C++

To open a PDF document.

1// open document from the filesystem
2PDFDoc doc(filename);
3
4// optionally read a PDF document from a stream
5MappedFile file(filename);
6PDFDoc doc_stream(file);
7
8// or pass-in a memory buffer
9size_t file_sz = file.FileSize();
10FilterReader file_reader(file);
11unsigned char* mem = new unsigned char[file_sz];
12file_reader.Read((unsigned char*)mem, file_sz);
13PDFDoc doc_mem(mem, file_sz);
14
15// loading from a URL requires an additional
16// library, e.g. "urdl" to use istream
17string file_content;
18int file_sz;
19istream url("https://myserver.com/myfile.pdf", ios::binary);
20getline(url, file_content, char_traits<char>::eof());
21file_sz = url.tellg();
22PDFDoc doc(file_content, file_sz);

Read & write a PDF file from/to memory buffer
Full source code which illustrates how to read/write a PDF document from/to memory buffer. This is useful for applications that work with dynamic PDF documents that don't need to be saved/read from a disk.

About opening a document

The PDFDoc constructor creates a PDF document from scratch:

PDFDoc.Close()

When you are finished with a PDFDoc object, the PDFDoc.Close() method should be called to clean up memory, file handles, and resources.

1PDFDoc doc;

A newly-created document does not yet contain any pages. See the accessing pages section for details on creating new pages and working with existing pages.

Using Apryse SDK, you can open a document from a serialized file, from a memory buffer, or from a Filter stream.

To open an existing PDF document from a file, specify its file path in the PDFDoc constructor:

1PDFDoc doc(filename);

Here's how to open an existing PDF document from a memory buffer:

1MappedFile file(filename);
2size_t file_sz = file.FileSize();
3FilterReader file_reader(file);
4unsigned char* mem = new unsigned char[file_sz];
5file_reader.Read((unsigned char*)mem, file_sz);
6PDFDoc doc(mem, file_sz);

It's also easy to open a PDF document from a MemoryFilter or a custom Filter .

After creating a PDFDoc object, it's good practice to call InitSecurityHandler() on it. If the document is encrypted, calling the method will decrypt it. If the document is not encrypted, calling the method is harmless.

1PDFDoc doc(filename);
2if (!doc.InitSecurityHandler())
3{
4 printf("Document authentication error...");
5 return;
6}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales