PdfFileSource
The PdfFileSource class represents the content of an existing PDF file.
Using PdfFileSource
Create an Instance
To create an instance of PdfFileSource, pass a FileStream object containing the PDF document to the constructor of the class.
Example 1: Create a PdfFileSource
using (PdfFileSource fileSource = new PdfFileSource(File.OpenRead(path)))
{
//...
}
PdfFileSource also exposes an additional overload that allows you to keep the stream open after disposing the PdfFileSource instance. Pass true as the value for the second constructor parameter (leaveStreamOpen).
You can also use the overload that accepts a parameter of type PdfImportSettings. This overload enables you to handle password-encrypted documents.
Example 2: Open encrypted document
public void ReadDocument(string path)
{
PdfImportSettings importSettings = new PdfImportSettings();
importSettings.UserPasswordNeeded += Settings_UserPasswordNeeded;
using (PdfFileSource fileSource = new PdfFileSource(File.OpenRead(path), importSettings, leaveStreamOpen: false))
{
//...
}
}
private void Settings_UserPasswordNeeded(object sender, PasswordNeededEventArgs e)
{
e.Password = "pass";
}
PdfFileSourceinherits from IDisposable. Ensure the object is disposed when you are done with it. The best way to handle this is to wrap it in ausingstatement.
Members
PdfFileSource exposes the Pages property, which is of type PdfPageSource[] and allows you to access the pages of the imported document.
Example 3: Iterate the pages of a document
using (PdfFileSource fileSource = new PdfFileSource(File.OpenRead(path)))
{
foreach (PdfPageSource pageSource in fileSource.Pages)
{
//...
}
}
You can use the indexer of the
Pagesproperty to obtain a specific page of the document and split it. Then, save the separated page withPdfStreamWriter.