One bitmap for viewing, another for printing (PDF)

When we render a chart to PDF (using iText), we want to render at 96dpi when displayed on the screen. If we use even 300dpi then when viewing on the screen very thin lines disappear. This makes the chart look all wrong. But when printing we want 600dpi, a 96dpi image looks really bad when printed.

Fortunately PDF has this functionality. You can make displaying a bitmap conditional on printing, zoom level, and more. The iText book demonstrates how to display print only and for zoom levels. But it does not demonstrate the display if not printing mode. So here’s how to do it where you display one image if printing and another if viewing. (Note: I did not put them at the same location so I could verify that one was not rendering over the other.) (source code)

static void Main(string[] args)
{

    Document document = new Document(new Rectangle(0, 0, 8.5f * 72.0f, 11 * 72));

    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Path.GetFullPath(@”..\..\test_dotnet.pdf”), FileMode.OpenOrCreate, FileAccess.ReadWrite));

    document.Open();

    document.Add(new Paragraph(“Visibility test”));

 

    // not displayed on printer

    PdfLayer layer = new PdfLayer(“screen”, writer);

    layer.OnPanel = false;

    layer.SetPrint(“Print”, false);

    layer.View = true;

    PdfContentByte cb = writer.DirectContent;

    cb.BeginLayer(layer);

    Image img = Image.GetInstance(Path.GetFullPath(@”..\..\building_01.png”));

    img.SetAbsolutePosition(72, 72 * 7);

    cb.AddImage(img);

    cb.EndLayer();

 

    // not displayed on screen

    layer = new PdfLayer(“print”, writer);

    layer.OnPanel = false;

    layer.SetPrint(“Print”, true);

    layer.View = false;

    cb = writer.DirectContent;

    cb.BeginLayer(layer);

    img = Image.GetInstance(Path.GetFullPath(@”..\..\building_02.png”));

    img.SetAbsolutePosition(72, 72 * 3);

    cb.AddImage(img);

    cb.EndLayer();

 

    document.Close();

    Console.Out.WriteLine(“all done”);

}