Skip to content

Instantly share code, notes, and snippets.

@pvginkel
Created May 29, 2015 10:24
Show Gist options
  • Save pvginkel/0826160bcae25372ad45 to your computer and use it in GitHub Desktop.
Save pvginkel/0826160bcae25372ad45 to your computer and use it in GitHub Desktop.
PdfPrintDocument
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
namespace PdfiumViewer
{
internal class PdfPrintDocument : PrintDocument
{
private readonly PdfDocument _document;
private readonly PdfPrintMode _printMode;
private int _currentPage;
public PdfPrintDocument(PdfDocument document, PdfPrintMode printMode)
{
if (document == null)
throw new ArgumentNullException("document");
_document = document;
_printMode = printMode;
}
protected override void OnBeginPrint(PrintEventArgs e)
{
_currentPage = PrinterSettings.FromPage == 0 ? 0 : PrinterSettings.FromPage - 1;
}
protected override void OnQueryPageSettings(QueryPageSettingsEventArgs e)
{
if (_currentPage < _document.PageCount)
e.PageSettings.Landscape = GetOrientation(_document.PageSizes[_currentPage]) == Orientation.Landscape;
}
protected override void OnPrintPage(PrintPageEventArgs e)
{
if (_currentPage < _document.PageCount)
{
var pageSize = _document.PageSizes[_currentPage];
var pageOrientation = GetOrientation(pageSize);
var printOrientation = GetOrientation(e.PageBounds.Size);
float scaleX = e.Graphics.VisibleClipBounds.Width / pageSize.Width;
float scaleY = e.Graphics.VisibleClipBounds.Height / pageSize.Height;
float scale = Math.Min(scaleX, scaleY);
var dpiX = e.Graphics.DpiX * scale;
var dpiY = e.Graphics.DpiY * scale;
_document.Render(
_currentPage++,
e.Graphics,
dpiX,
dpiY,
new Rectangle(
AdjustDpi(dpiX, e.Graphics.VisibleClipBounds.X),
AdjustDpi(dpiY, e.Graphics.VisibleClipBounds.Y),
AdjustDpi(dpiX, e.Graphics.VisibleClipBounds.Width),
AdjustDpi(dpiY, e.Graphics.VisibleClipBounds.Height)
),
true
);
}
int pageCount =
PrinterSettings.ToPage == 0
? _document.PageCount
: Math.Min(PrinterSettings.ToPage, _document.PageCount);
e.HasMorePages = _currentPage < pageCount;
}
private static int AdjustDpi(double value, double dpi)
{
return (int)((value / 96.0) * dpi);
}
private Orientation GetOrientation(SizeF pageSize)
{
if (pageSize.Height > pageSize.Width)
return Orientation.Portrait;
return Orientation.Landscape;
}
private enum Orientation
{
Portrait,
Landscape
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment