Skip to content

Commit

Permalink
Added MultipagePrintDocument example
Browse files Browse the repository at this point in the history
  • Loading branch information
falleretic committed Feb 1, 2020
1 parent c398d58 commit 28d5af3
Show file tree
Hide file tree
Showing 8 changed files with 357 additions and 0 deletions.
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29613.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MultipagePrintDocumentExample", "MultipagePrintDocumentExample\MultipagePrintDocumentExample.csproj", "{D3DA798D-215F-428D-83FF-7D39CEAC046A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D3DA798D-215F-428D-83FF-7D39CEAC046A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D3DA798D-215F-428D-83FF-7D39CEAC046A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D3DA798D-215F-428D-83FF-7D39CEAC046A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D3DA798D-215F-428D-83FF-7D39CEAC046A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FCAD1746-9BA2-4A00-8032-F06955C7A37A}
EndGlobalSection
EndGlobal
Binary file not shown.
@@ -0,0 +1,149 @@
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Drawing.Text;
using Aspose.Words;
using Aspose.Words.Rendering;

namespace MultipagePrintDocumentExample
{
internal class MultipagePrintDocument : PrintDocument
{
/// <summary>
/// Initializes a new instance of this class.
/// </summary>
/// <param name="document">The document to print.</param>
/// <param name="pagesPerSheet">The number of pages per one sheet.</param>
/// <param name="printPageBorder">The flag that indicates if the printed page borders are needed.</param>
public MultipagePrintDocument(Document document, int pagesPerSheet, bool printPageBorder)
{
if (document == null)
throw new ArgumentNullException("document");

mDocument = document;
mPagesPerSheet = pagesPerSheet;
mPrintPageBorder = printPageBorder;
}

/// <summary>
/// Called before the printing starts. Initializes the range of pages to be printed
/// according to the user selection.
/// </summary>
/// <param name="e">The event arguments.</param>
protected override void OnBeginPrint(PrintEventArgs e)
{
base.OnBeginPrint(e);

switch (PrinterSettings.PrintRange)
{
case PrintRange.AllPages:
mCurrentPage = 1;
mPageTo = mDocument.PageCount;
break;
case PrintRange.SomePages:
mCurrentPage = PrinterSettings.FromPage;
mPageTo = PrinterSettings.ToPage;
break;
default:
throw new InvalidOperationException("Unsupported print range.");
}

// Store the page size, selected by user, taking into account the paper orientation.
if (PrinterSettings.DefaultPageSettings.Landscape)
mPaperSize = new Size(PrinterSettings.DefaultPageSettings.PaperSize.Height,
PrinterSettings.DefaultPageSettings.PaperSize.Width);
else
mPaperSize = new Size(PrinterSettings.DefaultPageSettings.PaperSize.Width,
PrinterSettings.DefaultPageSettings.PaperSize.Height);

}

private static Size GetThumbCount(int pagesPerSheet)
{
switch (pagesPerSheet)
{
case 16: return new Size(4, 4);
case 9: return new Size(3, 3);
case 8: return new Size(4, 2);
case 6: return new Size(3, 2);
case 4: return new Size(2, 2);
case 2: return new Size(2, 1);
default: return new Size(1, 1);
}
}

/// <summary>
/// Called when each page is printed. This method actually renders the page to the graphics object.
/// </summary>
/// <param name="e">The event arguments.</param>
protected override void OnPrintPage(PrintPageEventArgs e)
{
base.OnPrintPage(e);

e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

// This gives us how many thumbnails we print across and down.
Size thumbCount = GetThumbCount(mPagesPerSheet);

// These are in "display" units (1/100 inch).
SizeF thumbSize = new SizeF((float)mPaperSize.Width / thumbCount.Width, (float)mPaperSize.Height / thumbCount.Height);

mPageTo = (mPageTo + mPagesPerSheet < mPageTo) ? mPageTo + mPagesPerSheet : mPageTo;

for (int pageIndex = mCurrentPage - 1; pageIndex < mPageTo; pageIndex++)
{
int dividend = pageIndex - (mCurrentPage - 1);
int rowIdx = dividend / thumbCount.Width;
int columnIdx = dividend % thumbCount.Width;

// This renders the page in the appropriate location and size given in world coordinates (1/100 inch in our case).
float thumbLeft = columnIdx * thumbSize.Width;
float thumbTop = rowIdx * thumbSize.Height;
// The useful return value is the scale at which the page was rendered.
float scale = mDocument.RenderToSize(pageIndex, e.Graphics, thumbLeft, thumbTop, thumbSize.Width, thumbSize.Height);

// This draws the page border (the page could be smaller than the thumbnail size).
if (mPrintPageBorder)
{
PageInfo pageInfo = mDocument.GetPageInfo(pageIndex);
// We know how much the page was scaled so we can draw the border around the scaled page now.
e.Graphics.DrawRectangle(Pens.Black, thumbLeft, thumbTop, WidthInHundredthsInch(pageInfo) * scale, HeightInHundredthsInch(pageInfo) * scale);
}

// This draws a border around the thumbnail.
e.Graphics.DrawRectangle(Pens.Red, thumbLeft, thumbTop, thumbSize.Width, thumbSize.Height);
}

mCurrentPage = mCurrentPage + mPagesPerSheet;
e.HasMorePages = (mCurrentPage <= mPageTo);
}

/// <summary>
/// Returns the width of the page in hundredths of an inch.
/// </summary>
private int WidthInHundredthsInch(PageInfo pageInfo)
{
double widthInInches = pageInfo.WidthInPoints / PointsPerInch;

return (int)Math.Round(widthInInches * 100);
}

/// <summary>
/// Returns the height of the page in hundredths of an inch.
/// </summary>
private int HeightInHundredthsInch(PageInfo pageInfo)
{
double heightInInches = pageInfo.HeightInPoints / PointsPerInch;

return (int)Math.Round(heightInInches * 100);
}

public const double PointsPerInch = 72.0;
private readonly Document mDocument;
private readonly int mPagesPerSheet;
private readonly bool mPrintPageBorder;
private Size mPaperSize = Size.Empty; // Initialized for Java to work.
private int mCurrentPage;
private int mPageTo;
}
}
@@ -0,0 +1,83 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D3DA798D-215F-428D-83FF-7D39CEAC046A}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>MultipagePrintDocumentExample</RootNamespace>
<AssemblyName>MultipagePrintDocumentExample</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="Aspose.Words, Version=20.1.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56, processorArchitecture=MSIL">
<HintPath>..\packages\Aspose.Words.20.1.0\lib\net35-client\Aspose.Words.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="MultipagePrintDocument.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,58 @@
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Aspose.Words;

namespace MultipagePrintDocumentExample
{
class Program
{
[STAThread]
static void Main(string[] args)
{
// Sample infrastructure.
string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;

Document doc = new Document(dataDir + "TestFile.docx");

PrintDialog printDlg = new PrintDialog();
// Initialize the print dialog with the number of pages in the document.
printDlg.AllowSomePages = true;
printDlg.PrinterSettings.MinimumPage = 1;
printDlg.PrinterSettings.MaximumPage = doc.PageCount;
printDlg.PrinterSettings.FromPage = 1;
printDlg.PrinterSettings.ToPage = doc.PageCount;

// Pass the printer settings from the print dialog to the print document.
MultipagePrintDocument awPrintDoc = new MultipagePrintDocument(doc, 4, true);
awPrintDoc.PrinterSettings = printDlg.PrinterSettings;

// Initialize the print preview dialog.
PrintPreviewDialog previewDlg = new PrintPreviewDialog();

// Pass the Aspose.Words print document to the print preview dialog.
previewDlg.Document = awPrintDoc;

// Specify additional parameters of the Print Preview dialog.
previewDlg.ShowInTaskbar = true;
previewDlg.MinimizeBox = true;
previewDlg.PrintPreviewControl.Zoom = 1;
previewDlg.Document.DocumentName = doc.OriginalFileName;
previewDlg.WindowState = FormWindowState.Maximized;

// Occur whenever the print preview dialog is first displayed.
previewDlg.Shown += PreviewDlg_Shown;

// Show the appropriately configured Print Preview dialog.
previewDlg.ShowDialog();
}

private static void PreviewDlg_Shown(object sender, EventArgs e)
{
// Bring the print preview dialog on top when it is initially displayed.
((PrintPreviewDialog)sender).Activate();
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MultipagePrintDocumentExample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MultipagePrintDocumentExample")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d3da798d-215f-428d-83ff-7d39ceac046a")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Aspose.Words" version="20.1.0" targetFramework="net35" />
</packages>
@@ -0,0 +1,2 @@
# Multipage Print Document by Aspose.Words for .NET 1.2
The MultipagePrintDocument class provides the ability to print several pages on one sheet of paper.

0 comments on commit 28d5af3

Please sign in to comment.