PrintManager – Setting Advanced Printer Options

by Anil S Mon, April 27 2015, 10:24 AM (US Eastern Time)

The PrintManager for .NET API allows printing of PDF files through any .NET application.  The settings accessible to the PrintManager are limited to those exposed through a standard API (such as Win32 or .NET).  But a printer may have additional settings that are specific to that printer and are not readily available through a standard API. This means that there could be non-standard features or settings available that vary between printers that are not able to be exposed through the PrintManager API.  To remedy this, we have exposed a way to manually save and reuse a specific state of the native printer’s dialog box that when provided to the Printjob will affect that job as if those options where manually selected by a user.  A full example on how to accomplish this is outlined below.

We will start with the code to invoke printer’s native dialog box and save the settings to a file.

To invoke the printer's advanced setting dialog we will be using a Win32 function called "AdvancedDocumentProperties".

AdvancedDocumentProperties(IntPtr.Zero,IntPtr.Zero,e.PrintJob.Printer.Name,e.DevMode, e.DevMode);

In order to import the above function to a .NET application, use the following DllImport.

[DllImport("winspool.Drv", EntryPoint = "AdvancedDocumentPropertiesW", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]

static extern int AdvancedDocumentProperties(IntPtr hwnd, IntPtr hPrinter, [MarshalAs(UnmanagedType.LPWStr)] string pDeviceName, IntPtr pDevModeOutput, IntPtr pDevModeInput);

Calling the Print() method will fire the Printjob.Starting event. In the event handler, call AdvancedDocumentProperties to display the printer setting dialog box. Select the appropriate setting that you would like to save to file and click OK. The file can be generated with individual settings or with a group of settings.

PrintJob printJob = new PrintJob(Printer.Default, "DocumentA.pdf");

printJob.Starting += new PrintJobStartingEventHandler(this.onStartingPrint1);

printJob.Print();

PrintJobStartingEventArgs contains following properties that will be used to retrieve the printer settings from the dialog box.

Name Type Definition
Devmode Intptr Pointer towards Devmode structure
DevmodeSize Int Size of  Devmode
DevmodeDriverExtra Int Size of  DmDriverExtra
PrintJob PrintJob DynamicPDF Printmanager PrintJob object. Generic printer settings can be changed using this object.

Here is the code for the event handler to retrieve and save the selected printer setting.

private void onStartingPrint1(object sender, PrintJobStartingEventArgs e)
{
    //Invoke the printer options dialog box.
    int value = AdvancedDocumentProperties(IntPtr.Zero, IntPtr.Zero, e.PrintJob.Printer.Name, e.DevMode, e.DevMode);

    //Create a byte array to store Devmode and DmDriverExtra settings.
    byte[] bytearray = new byte[e.DevModeSize + e.DevModeDriverExtra];

    //Copy the contents of both Devmode and DmDriverExtra to the byte array.
    Marshal.Copy(e.DevMode, bytearray, 0, e.DevModeSize + e.DevModeDriverExtra);

    //Save the settings to disk.
    File.WriteAllBytes("SettingsFile.bin", bytearray); 
}

Next, we will print a PDF using the saved settings by overwriting the Devmode and DmDriverExtra structures with the file contents. Due to this, all settings applied to the PrintJob object before Printjob.Starting event handler call will be lost. However we can set the print settings after overwriting Devmode and DmDriverExtra in the event handler.

private void onStartingPrint2(object sender, PrintJobStartingEventArgs e)
{
    //Load the saved settings into a byte array. 
    byte[] bytearray = File.ReadAllBytes("SettingsFile.bin");

    //Overwrite the DevMode with the byte array restored from file. 
    IntPtr pdevmode = Marshal.AllocHGlobal(bytearray.Length);
    Marshal.Copy(bytearray, 0, e.DevMode, bytearray.Length);

    //The line below displays the print options dialog box, so the modified settings can be verified during development. 
    //It is not required for printing so it can removed, especially for non-interactive applications like windows services             
    int value = AdvancedDocumentProperties(IntPtr.Zero, IntPtr.Zero, e.PrintJob.Printer.Name, e.DevMode, e.DevMode);            

    //Set additional print settings as needed. 
    e.PrintJob.PrintOptions.Copies = 1;
}

Complete source code is available for download below.

Downloads:

PrinterAdvancedOptions.zip (21.2 kb)

Tags: , , , , ,

Creating PDFs in C# with Outlined or Invisible Text

by Andy C Thu, August 30 2012, 1:51 PM (US Eastern Time)

DynamicPDF Generator has lots of predefined page elements which allow you to easily create different types of content, but you may occasionally have a need to do something that is not available in the API by default. Custom page elements is an easy way to extend the API to achieve these results.

We get questions from time to time on how to add outlined text to a PDF. By outlined text I mean text that is not completely filled in with a color but rather is just an outline of the font and nothing filled in the middle of the text.  This is a great situation for using a Custom page element and the C# code below shows how to extend the TextArea page element to add this functionality:

using System;
using ceTe.DynamicPDF;
using ceTe.DynamicPDF.PageElements;

public class OutlinedTextArea : TextArea
{
    // Member variable to store Border Width
    private float borderWidth = 1.0f;

    // Constructors. Additional ones can be added to model TextArea
    public OutlinedTextArea(string text, float x, float y, float width, float height)
        : base(text, x, y, width, height) { }
    public OutlinedTextArea(string text, float x, float y, float width, float height,
        Font font, float fontSize)
        : base(text, x, y, width, height, font, fontSize) { }

    // Border Width Property added
    public float BorderWidth
    {
        get { return this.borderWidth; }
        set { this.borderWidth = value; }
    }

    // Override Draw Method
    public override void Draw(ceTe.DynamicPDF.IO.PageWriter writer)
    {
        // Enter Graphics Mode
        writer.SetGraphicsMode();
        // Set Stroke Color and Border Width
        writer.SetStrokeColor(base.TextColor);
        writer.SetLineWidth(this.borderWidth);
        // Enter Text Mode
        writer.SetTextMode();
        // Set Text Rendering Mode
        writer.SetTextRenderingMode(TextRenderingMode.Stroke);
        // Call Draw on base class
        base.Draw(writer);
        // Enter Text Mode (in case underline is set to true)
        writer.SetTextMode();
        // Set Text Rendering Mode Back to Fill
        writer.SetTextRenderingMode(TextRenderingMode.Fill);
    }
}

More...

Tags: , , , , , , , , , , ,

Create AES Encrypted PDFs in C# and VB .NET

by Andy C Tue, July 31 2012, 2:48 PM (US Eastern Time)

We recently released an update that introduces AES-256 bit and AES-128 bit encryption to our .NET PDF creation and merging library. We have offered encryption since 2002, but this was limited to RC4-40 bit and RC4-128 bit security until this release. We have also restructured the API a bit in order to easily accommodate new encryption methods in the future.

Encryption is now handled by 4 classes in a new ceTe.DynamicPDF.Cryptography namespace:

All security classes allow restrictions to be placed on a PDF to restrict printing, modification, copying content or updating/adding text annotations or form fields. The 128-bit and higher classes allow restrictions to be placed on a PDF to restrict filling in existing form fields, extracting text and graphics for accessibility purposes, modifying the pages included, high resolution printing or leaving the XMP metadata unencrypted. The AES classes also add the ability to encrypt only file attachments.

The C# code to add AES-256 bit encryption to a new document is very straight forward:

Document document = new Document();
Page page = new Page();
page.Elements.Add(new Label("AES-256 bit encrypted PDF.", 0, 0, 500, 15));
document.Pages.Add(page);
// Add the encryption
Aes256Security security = new Aes256Security("ownerpassword", "userpassword");
security.AllowHighResolutionPrinting = false;
// Set other encryption options
document.Security = security;
// Output the PDF
document.Draw("MyPDF.pdf");

More...

Tags: , , , ,

Splitting a PDF from .NET (C# Code Provided)

by Anil S Tue, May 22 2012, 1:47 PM (US Eastern Time)

We get a decent amount of people who ask us about dynamically splitting a PDF.  Splitting a PDF document using DynamicPDF Merger for .Net is a very simple task. With the few lines of code the document can be split efficiently at the desired page. Use of PdfDocument object allows for efficient reuse of imported PDF document data. If the same PDF needs to be reused in multiple parts of the application, load the PDF into a PdfDocument object and use it where ever needed. Also the PdfDocument object is designed to be thread safe.
 
Let’s take a look at an example where we want to take a PDF file (pdfToSplit.pdf) and split it into two files (pdfA.pdf and pdfB.pdf).  The first PDF split (pdfA.pdf) will contain the first 50 pages of the file while the second PDF (pdfB.pdf) will contain all remaining pages.  Notice that we do not need to know how many pages the original PDF contained by utilizing the PdfDocument’s Pages.Count method.

            //Create a PdfDocument object to load the PDF.
            PdfDocument pdfToSplit = new PdfDocument("pdfToSplit.pdf");

            //Page number to split the document at. 
            int pageNumToSplit = 50;

            //Add first 50 pages and call the Draw method to save the PDF. 
            MergeDocument firstPdf = new MergeDocument(pdfToSplit, 1, pageNumToSplit);
            firstPdf.Draw("pdfA.pdf");

            //Add the remaining pages to a second document and save the PDF. 
            MergeDocument secondPDF = new MergeDocument(pdfToSplit, pageNumToSplit + 1, pdfToSplit.Pages.Count - pageNumToSplit);
            secondPDF.Draw("pdfB.pdf");

More...

Tags: , , , ,