PDF: Рендеринг PDF страницы
В этом разделе
Формат PDF - векторный формат, поэтому для получения PDF страницы в виде растрового изображения ее необходимо отрендерить. Для рендеринга PDF страницы используется метод
PdfPage.Render. Свойство
PdfDocument.RenderingSettings определяет настройки рендеринга по умолчанию для каждой страницы PDF документа.
Метод
PdfPage.Render может вернуть все изображение страницы или только ее часть. Изображение страницы может быть отрендерено в любом разрешении. Если разрешение рендеринга не задано, то используется разрешение 96x96 точек на дюйм.
Вот C#/VB.NET код, который демонстрирует, как отрендерить PDF страницу с разрешением 300x300 dpi:
/// <summary>
/// Gets PDF page with 300x300 resolution.
/// </summary>
/// <param name="page">The page of PDF document.</param>
public static Vintasoft.Imaging.VintasoftImage GetImage300dpi(
Vintasoft.Imaging.Pdf.Tree.PdfPage page)
{
// get the rendering settings of PDF document
Vintasoft.Imaging.Codecs.Decoders.PdfRenderingSettings renderingSettings = page.Document.RenderingSettings;
// save previous resolution of rendering settings
Vintasoft.Imaging.Resolution prevResolution = renderingSettings.Resolution;
// set new resolution for image rendering
renderingSettings.Resolution = new Vintasoft.Imaging.Resolution(300, 300);
// render image of the page
Vintasoft.Imaging.VintasoftImage image = page.Render();
// restore resolution of rendering settings
renderingSettings.Resolution = prevResolution;
// return the image
return image;
}
''' <summary>
''' Gets PDF page with 300x300 resolution.
''' </summary>
''' <param name="page">The page of PDF document.</param>
Public Shared Function GetImage300dpi(page As Vintasoft.Imaging.Pdf.Tree.PdfPage) As Vintasoft.Imaging.VintasoftImage
' get the rendering settings of PDF document
Dim renderingSettings As Vintasoft.Imaging.Codecs.Decoders.PdfRenderingSettings = page.Document.RenderingSettings
' save previous resolution of rendering settings
Dim prevResolution As Vintasoft.Imaging.Resolution = renderingSettings.Resolution
' set new resolution for image rendering
renderingSettings.Resolution = New Vintasoft.Imaging.Resolution(300, 300)
' render image of the page
Dim image As Vintasoft.Imaging.VintasoftImage = page.Render()
' restore resolution of rendering settings
renderingSettings.Resolution = prevResolution
' return the image
Return image
End Function
Вот C#/VB.NET код, который демонстрирует, как отрендерить область PDF страницы с разрешением 600x600 dpi:
/// <summary>
/// Gets region of PDF page with 600x600 resolution.
/// </summary>
/// <param name="page">The page of PDF document.</param>
/// <param name="region">The region of page.</param>
public static Vintasoft.Imaging.VintasoftImage GetImage600dpiRegion(
Vintasoft.Imaging.Pdf.Tree.PdfPage page, System.Drawing.RectangleF region)
{
// get the rendering settings of PDF document
Vintasoft.Imaging.Codecs.Decoders.PdfRenderingSettings renderingSettings = page.Document.RenderingSettings;
// save previous resolution of rendering settings
Vintasoft.Imaging.Resolution prevResolution = renderingSettings.Resolution;
// set new resolution for image rendering
renderingSettings.Resolution = new Vintasoft.Imaging.Resolution(600, 600);
// render region of PDF page
Vintasoft.Imaging.VintasoftImage image = page.Render(region, 1.0f);
// restore resolution of rendering settings
renderingSettings.Resolution = prevResolution;
// return the image
return image;
}
''' <summary>
''' Gets region of PDF page with 600x600 resolution.
''' </summary>
''' <param name="page">The page of PDF document.</param>
''' <param name="region">The region of page.</param>
Public Shared Function GetImage600dpiRegion(page As Vintasoft.Imaging.Pdf.Tree.PdfPage, region As System.Drawing.RectangleF) As Vintasoft.Imaging.VintasoftImage
' get the rendering settings of PDF document
Dim renderingSettings As Vintasoft.Imaging.Codecs.Decoders.PdfRenderingSettings = page.Document.RenderingSettings
' save previous resolution of rendering settings
Dim prevResolution As Vintasoft.Imaging.Resolution = renderingSettings.Resolution
' set new resolution for image rendering
renderingSettings.Resolution = New Vintasoft.Imaging.Resolution(600, 600)
' render region of PDF page
Dim image As Vintasoft.Imaging.VintasoftImage = page.Render(region, 1F)
' restore resolution of rendering settings
renderingSettings.Resolution = prevResolution
' return the image
Return image
End Function
Рендеринг PDF страницы может выполняться с индикацией прогресса выполнения. Также можно отменить рендеринг страницы.
Вот C#/VB.NET код, который демонстрирует, как отрендерить PDF страницу с индикацией прогресса и отменить процесс рендеринга на уровне 80%:
/// <summary>
/// Cancels rendering of PDF page when progress of rendering is greater than 80%.
/// </summary>
/// <param name="page">The page of PDF document.</param>
public static void CancelRenderingExample(Vintasoft.Imaging.Pdf.Tree.PdfPage page)
{
// render image of PDF page
page.Render(new System.EventHandler<Vintasoft.Imaging.ProgressEventArgs>(RenderingProgress));
}
/// <summary>
/// Event handler of rendering progress.
/// </summary>
public static void RenderingProgress(object sender, Vintasoft.Imaging.ProgressEventArgs e)
{
// if rendering canbe canceled and rendering progress is geater than 80%
if (e.CanCancel && e.Progress >= 80)
// cancel rendering
e.Cancel = true;
}
''' <summary>
''' Cancels rendering of PDF page when progress of rendering is greater than 80%.
''' </summary>
''' <param name="page">The page of PDF document.</param>
Public Shared Sub CancelRenderingExample(page As Vintasoft.Imaging.Pdf.Tree.PdfPage)
' render image of PDF page
page.Render(New System.EventHandler(Of Vintasoft.Imaging.ProgressEventArgs)(AddressOf RenderingProgress))
End Sub
''' <summary>
''' Event handler of rendering progress.
''' </summary>
Public Shared Sub RenderingProgress(sender As Object, e As Vintasoft.Imaging.ProgressEventArgs)
' if rendering canbe canceled and rendering progress is geater than 80%
If e.CanCancel AndAlso e.Progress >= 80 Then
' cancel rendering
e.Cancel = True
End If
End Sub
Также метод
PdfPage.Render поддерживает прогрессивный рендеринг PDF страницы.
Вот C#/VB.NET код, который демонстрирует, как отрендерить PDF страницу прогрессивно:
/// <summary>
/// The timer for getting intermediate images.
/// </summary>
public System.Diagnostics.Stopwatch _timer = new System.Diagnostics.Stopwatch();
/// <summary>
/// The index of intermediate image.
/// </summary>
public int _intermediateImageIndex = 0;
/// <summary>
/// Time interval, in milliseconds, for getting intermediate image during rendering.
/// </summary>
public int INTERMEDIATE_RENDER_IMAGE_INTERVAL = 300;
/// <summary>
/// Gets the image of PDF page.
/// </summary>
/// <param name="page">The page of PDF document.</param>
public Vintasoft.Imaging.VintasoftImage RenderPdfPageProgressively(
Vintasoft.Imaging.Pdf.Tree.PdfPage page)
{
_intermediateImageIndex = 0;
// start timer
_timer.Start();
// render PDF page progressively
Vintasoft.Imaging.VintasoftImage image = page.Render(page.CropBox, 1.0f, null,
new System.EventHandler<Vintasoft.Imaging.ImageRendering.IntermediateImageRequestEventArgs>(IntermediateImageRequest));
// stop timer
_timer.Stop();
// return the result image
return image;
}
/// <summary>
/// Handler of event that occurs when intermediate image is ready and can be obtained.
/// </summary>
public void IntermediateImageRequest(object sender, Vintasoft.Imaging.ImageRendering.IntermediateImageRequestEventArgs e)
{
// if intermediate image must be saved
if (_timer.ElapsedMilliseconds >= INTERMEDIATE_RENDER_IMAGE_INTERVAL)
{
// reset timer
_timer.Reset();
// set the delegate which invoked for obtaining the intermediate image
e.IntermediateImageCompleted =
new Vintasoft.Imaging.ImageRendering.IntermediateImageCompletedDelegate(IntermediateImageReady);
// start timer
_timer.Start();
}
}
/// <summary>
/// Delegate that allows to obtain intermediate image.
/// </summary>
public void IntermediateImageReady(Vintasoft.Imaging.ImageRendering.IntermediateImageReadyEventArgs e)
{
// increment counter of intermediate images
_intermediateImageIndex++;
// clone the rendered image
using (Vintasoft.Imaging.VintasoftImage image =
(Vintasoft.Imaging.VintasoftImage)e.Image.Clone())
{
string filename = string.Format("IntermediateImage_{0}.bmp", _intermediateImageIndex.ToString("00"));
// save the intermediate image to a file
image.Save(filename);
}
}
''' <summary>
''' The timer for getting intermediate images.
''' </summary>
Public _timer As New System.Diagnostics.Stopwatch()
''' <summary>
''' The index of intermediate image.
''' </summary>
Public _intermediateImageIndex As Integer = 0
''' <summary>
''' Time interval, in milliseconds, for getting intermediate image during rendering.
''' </summary>
Public INTERMEDIATE_RENDER_IMAGE_INTERVAL As Integer = 300
''' <summary>
''' Gets the image of PDF page.
''' </summary>
''' <param name="page">The page of PDF document.</param>
Public Function RenderPdfPageProgressively(page As Vintasoft.Imaging.Pdf.Tree.PdfPage) As Vintasoft.Imaging.VintasoftImage
_intermediateImageIndex = 0
' start timer
_timer.Start()
' render PDF page progressively
Dim image As Vintasoft.Imaging.VintasoftImage = page.Render(page.CropBox, 1F, Nothing, New System.EventHandler(Of Vintasoft.Imaging.ImageRendering.IntermediateImageRequestEventArgs)(AddressOf IntermediateImageRequest))
' stop timer
_timer.[Stop]()
' return the result image
Return image
End Function
''' <summary>
''' Handler of event that occurs when intermediate image is ready and can be obtained.
''' </summary>
Public Sub IntermediateImageRequest(sender As Object, e As Vintasoft.Imaging.ImageRendering.IntermediateImageRequestEventArgs)
' if intermediate image must be saved
If _timer.ElapsedMilliseconds >= INTERMEDIATE_RENDER_IMAGE_INTERVAL Then
' reset timer
_timer.Reset()
' set the delegate which invoked for obtaining the intermediate image
e.IntermediateImageCompleted = New Vintasoft.Imaging.ImageRendering.IntermediateImageCompletedDelegate(AddressOf IntermediateImageReady)
' start timer
_timer.Start()
End If
End Sub
''' <summary>
''' Delegate that allows to obtain intermediate image.
''' </summary>
Public Sub IntermediateImageReady(e As Vintasoft.Imaging.ImageRendering.IntermediateImageReadyEventArgs)
' increment counter of intermediate images
_intermediateImageIndex += 1
' clone the rendered image
Using image As Vintasoft.Imaging.VintasoftImage = DirectCast(e.Image.Clone(), Vintasoft.Imaging.VintasoftImage)
Dim filename As String = String.Format("IntermediateImage_{0}.bmp", _intermediateImageIndex.ToString("00"))
' save the intermediate image to a file
image.Save(filename)
End Using
End Sub
Рендеринг PDF страниц с аннотациями
PDF cтраница может быть отрендерена с аннотациями или без них.
Вот C#/VB.NET код, который демонстрирует, как отрендерить PDF страницу с аннотациями:
/// <summary>
/// Renders PDF page with the PDF annotations.
/// </summary>
/// <param name="page">The page of PDF document.</param>
public static Vintasoft.Imaging.VintasoftImage RenderPdfPageWithPdfAnnotations(
Vintasoft.Imaging.Pdf.Tree.PdfPage page)
{
// get rendering settings of PDF page
Vintasoft.Imaging.Codecs.Decoders.PdfRenderingSettings renderingSettings = page.Document.RenderingSettings;
// save previous value of PdfRenderingSettings.DrawPdfAnnotations property
bool prevDrawPdfAnnotations = renderingSettings.DrawPdfAnnotations;
// enable rendering of PDF annotations on PDF page
renderingSettings.DrawPdfAnnotations = true;
// render PDF page
Vintasoft.Imaging.VintasoftImage image = page.Render();
// restore value of PdfRenderingSettings.DrawPdfAnnotations property
renderingSettings.DrawPdfAnnotations = prevDrawPdfAnnotations;
// return the image of PDF page
return image;
}
''' <summary>
''' Renders PDF page with the PDF annotations.
''' </summary>
''' <param name="page">The page of PDF document.</param>
Public Shared Function RenderPdfPageWithPdfAnnotations(page As Vintasoft.Imaging.Pdf.Tree.PdfPage) As Vintasoft.Imaging.VintasoftImage
' get rendering settings of PDF page
Dim renderingSettings As Vintasoft.Imaging.Codecs.Decoders.PdfRenderingSettings = page.Document.RenderingSettings
' save previous value of PdfRenderingSettings.DrawPdfAnnotations property
Dim prevDrawPdfAnnotations As Boolean = renderingSettings.DrawPdfAnnotations
' enable rendering of PDF annotations on PDF page
renderingSettings.DrawPdfAnnotations = True
' render PDF page
Dim image As Vintasoft.Imaging.VintasoftImage = page.Render()
' restore value of PdfRenderingSettings.DrawPdfAnnotations property
renderingSettings.DrawPdfAnnotations = prevDrawPdfAnnotations
' return the image of PDF page
Return image
End Function
Рендеринг PDF страниц с использованием опциональных групп контента (OCG)
PDF страница может быть отрендерена с использованием опциональных групп контента (OCG), которые иногда называют слоями. SDK позволяет получить список слоев и показать/скрыть указанные слои при рендеринге PDF страницы.
Вот C#/VB.NET код, который демонстрирует, как отрендерить PDF страницы с использованием опциональных групп контента:
/// <summary>
/// Renders PDF page with the optional content group.
/// </summary>
/// <param name="page">The page of PDF document.</param>
public static Vintasoft.Imaging.VintasoftImage RenderPdfPageWithOptionalContentGroup(
Vintasoft.Imaging.Pdf.Tree.PdfPage page)
{
// get PDF document of page
Vintasoft.Imaging.Pdf.PdfDocument document = page.Document;
// if document has optional content groups then
if (document.OptionalContentProperties != null &&
document.OptionalContentProperties.OptionalContentGroups != null)
{
// get a list of optional content groups of PDF document
System.Collections.Generic.IList<Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup> allGroups =
document.OptionalContentProperties.OptionalContentGroups;
// for each optional content group
foreach (Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup group in allGroups)
// set the optional content group as invisible
document.OptionalContentConfiguration.SetGroupVisibility(group, false);
}
// render PDF page
Vintasoft.Imaging.VintasoftImage image = page.Render();
// return the image of PDF page
return image;
}
''' <summary>
''' Renders PDF page with the optional content group.
''' </summary>
''' <param name="page">The page of PDF document.</param>
Public Shared Function RenderPdfPageWithOptionalContentGroup(page As Vintasoft.Imaging.Pdf.Tree.PdfPage) As Vintasoft.Imaging.VintasoftImage
' get PDF document of page
Dim document As Vintasoft.Imaging.Pdf.PdfDocument = page.Document
' if document has optional content groups then
If document.OptionalContentProperties IsNot Nothing AndAlso document.OptionalContentProperties.OptionalContentGroups IsNot Nothing Then
' get a list of optional content groups of PDF document
Dim allGroups As System.Collections.Generic.IList(Of Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup) = document.OptionalContentProperties.OptionalContentGroups
' for each optional content group
For Each group As Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup In allGroups
' set the optional content group as invisible
document.OptionalContentConfiguration.SetGroupVisibility(group, False)
Next
End If
' render PDF page
Dim image As Vintasoft.Imaging.VintasoftImage = page.Render()
' return the image of PDF page
Return image
End Function
Управление цветом при рендеринге PDF страницы
PDF страница может быть отрендерена с включенным управлением цветом. Свойство
PdfDocument.DecodingSettings определяет настройки управления цветом по умолчанию, которые должны использоваться при рендеринге PDF страницы.
Вот C#/VB.NET код, который демонстрирует, как отрендерить PDF страницу с включенным управлением цветом:
/// <summary>
/// Renders PDF page with enabled color management.
/// </summary>
/// <param name="page">The PDF page.</param>
/// <param name="iccProfile">The ICC profile that should be applied to PDF page.</param>
public static Vintasoft.Imaging.VintasoftImage RenderPdfPageWithEnabledColorManagement(
Vintasoft.Imaging.Pdf.Tree.PdfPage page,
Vintasoft.Imaging.ColorManagement.Icc.IccProfile iccProfile)
{
// if decoding settings are NOT specified
if (page.Document.DecodingSettings == null)
// create the default decoding settings
page.Document.DecodingSettings = new Vintasoft.Imaging.Codecs.Decoders.DecodingSettings();
// get the decoding setting of PDF document
Vintasoft.Imaging.Codecs.Decoders.DecodingSettings decodingSettings = page.Document.DecodingSettings;
// if color management decoding settings is NOT enabled
if (decodingSettings.ColorManagement == null)
// create the default color management decoding settings
decodingSettings.ColorManagement = new Vintasoft.Imaging.ColorManagement.ColorManagementDecodeSettings();
// set the ICC profile that should be applied to PDF page
decodingSettings.ColorManagement.InputCmykProfile = iccProfile;
// render PDF page
Vintasoft.Imaging.VintasoftImage image = page.Render();
// return the image of PDF page
return image;
}
''' <summary>
''' Renders PDF page with enabled color management.
''' </summary>
''' <param name="page">The PDF page.</param>
''' <param name="iccProfile">The ICC profile that should be applied to PDF page.</param>
Public Shared Function RenderPdfPageWithEnabledColorManagement(page As Vintasoft.Imaging.Pdf.Tree.PdfPage, iccProfile As Vintasoft.Imaging.ColorManagement.Icc.IccProfile) As Vintasoft.Imaging.VintasoftImage
' if decoding settings are NOT specified
If page.Document.DecodingSettings Is Nothing Then
' create the default decoding settings
page.Document.DecodingSettings = New Vintasoft.Imaging.Codecs.Decoders.DecodingSettings()
End If
' get the decoding setting of PDF document
Dim decodingSettings As Vintasoft.Imaging.Codecs.Decoders.DecodingSettings = page.Document.DecodingSettings
' if color management decoding settings is NOT enabled
If decodingSettings.ColorManagement Is Nothing Then
' create the default color management decoding settings
decodingSettings.ColorManagement = New Vintasoft.Imaging.ColorManagement.ColorManagementDecodeSettings()
End If
' set the ICC profile that should be applied to PDF page
decodingSettings.ColorManagement.InputCmykProfile = iccProfile
' render PDF page
Dim image As Vintasoft.Imaging.VintasoftImage = page.Render()
' return the image of PDF page
Return image
End Function