Aperçu d'exemples

Content Addition | Document Setup | Imposition | Information Extraction

Content Addition

Add barcode to PDF

Generate and add a barcode at a specified position on the first page of a PDF document.

l'exemple C# :
// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create file stream
using (Stream fontStream = new FileStream(fontPath, FileMode.Open, FileAccess.Read))

// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, inDoc.Conformance, null))
using (Font font = outDoc.CreateFont(fontStream, true))
{
    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Set copy options
    CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | 
        CopyOption.CopyFormFields | CopyOption.CopyOutlines | CopyOption.CopyLogicalStructure;

    // Loop through all pages of input
    for (int i = 0; i < inDoc.Pages.Count; i++)
    {
        // Copy page from input to output
        using (Page inPage = inDoc.Pages[i])
        using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
        {
            if (i == 0)
            {
                // Add barcode to first page
                AddBarcode(outDoc, outPage, barcode, font, 50);
            }
            // Add page to document
            outDoc.Pages.Add(outPage);
        }
    }
}
private static void AddBarcode(Document outputDoc, Page outPage, string barcode, 
Font font, double fontSize)
{
    // Create content generator 
    using (ContentGenerator gen = new ContentGenerator(outPage.Content, false))
    {
        // Create text object
        using (Text barcodeText = outputDoc.CreateText())
        {
            // Create text generator
            using (TextGenerator textGenerator = new TextGenerator(barcodeText, font, 
                fontSize, null))
            {
                // Calculate position
                Point position = new Point
                {
                    X = outPage.Size.Width - (textGenerator.GetWidth(barcode) + Border),
                    Y = outPage.Size.Height - (fontSize * (font.Ascent + font.Descent) + Border)
                };

                // Move to position
                textGenerator.MoveTo(position);
                // Add given barcode string
                textGenerator.ShowLine(barcode);
            }
            // Paint the positioned barcode text
            gen.PaintText(barcodeText);
        }
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create file stream 
fontStream = new FileStream(fontPath, "r");

// Create output document
outStream = new FileStream(outPath, "rw");
outStream.setLength(0); 
outDoc = Document.create(outStream, inDoc.getConformance(), null);

// Create embedded font in output document
Font font = outDoc.createFont(fontStream, true);

// Set output intent
if (inDoc.getOutputIntent() != null) 
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Copy metadata
Metadata metadata =  outDoc.copyMetadata(inDoc.getMetadata());
outDoc.setMetadata(metadata);

// Set copy options
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS,
        CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Loop through all pages of input
for (int i = 0; i < inDoc.getPages().size(); i ++)
{
    Page inPage = inDoc.getPages().get(i);

    // Copy page from input to output
    Page outPage = outDoc.copyPage(inPage, copyOptions);

    if (i == 0)
    {
        // Add barcode to first page
        addBarcode(outDoc, outPage, barcode, font, 50);
    }

    // Add page to output document
    outDoc.getPages().add(outPage);

    // Cleanup
    outPage.close();
    inPage.close();
}
private static void addBarcode(Document outputDoc, Page outPage, String barcode, Font font,
double fontSize) throws ErrorCodeException 
{

    ContentGenerator generator = null;

    try
    {
        // Create content generator 
        generator = new ContentGenerator(outPage.getContent(), false);

        // Create text object
        Text barcodeText = outputDoc.createText();

        // Create a text generator
        TextGenerator textgenerator = new TextGenerator(barcodeText, font, fontSize, null);

        // Calculate position
        Point position = new Point(
                outPage.getSize().width - (textgenerator.getWidth(barcode) + Border),
                outPage.getSize().height - (fontSize * (font.getAscent() + 
                font.getDescent()) + Border)
                );

        // Move to position
        textgenerator.moveTo(position);
        // Add given barcode string
        textgenerator.showLine(barcode);
        // Close text generator
        textgenerator.close();

        // Paint the positioned barcode text
        generator.paintText(barcodeText);
    }
    finally
    {
       // Close content generator
        if (generator != null)
            generator.close();
    }
}

Add Data Matrix to PDF

Add a two-dimensional barcode from an existing image on the first page of a PDF document.

l'exemple C# :
// Open input document 
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
{
    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Set copy options
    CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | 
        CopyOption.CopyFormFields | CopyOption.CopyOutlines | CopyOption.CopyLogicalStructure;

    // Loop through all pages of input
    for (int i = 0; i < inDoc.Pages.Count; i++)
    {
        // Copy page from input to output
        using (Page inPage = inDoc.Pages[i])
        using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
        {
            if (i == 0)
            {
                // Add data matrix as image to first page
                AddDataMatrix(outDoc, outPage, datamatrixPath);
            }
            // Add page to document
            outDoc.Pages.Add(outPage);
        }
    }
}
private static void AddDataMatrix(Document document, Page page, string datamatrixPath)
{
    // Create content generator
    using (ContentGenerator generator = new ContentGenerator(page.Content, false))
    // Import data matrix
    using (Stream inMatrix = new FileStream(datamatrixPath, FileMode.Open, FileAccess.Read))
    // Create image object for data matrix
    using (Image datamatrix = document.CreateImage(inMatrix))
    {
        // Data matrix size
        double datamatrixSize = 85;

        // Calculate Rectangle for data matrix
        Rectangle rect = new Rectangle
        {
            Left = Border,
            Bottom = page.Size.Height - (datamatrixSize + Border),
            Right = datamatrixSize + Border,
            Top = page.Size.Height - Border
        };

        // Paint image of data matrix into the specified rectangle 
        generator.PaintImage(datamatrix, rect);
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create output document
outStream = new FileStream(outPath, "rw");
outStream.setLength(0); 
outDoc = Document.create(outStream, Conformance.UNKNOWN, null);

// Set output intent
if (inDoc.getOutputIntent() != null)
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Copy metadata
Metadata metadata =  outDoc.copyMetadata(inDoc.getMetadata());
outDoc.setMetadata(metadata);

// Set copy options
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS,
        CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Loop through all pages of input
for (int i = 0; i < inDoc.getPages().size(); i ++)
{
    Page inPage = inDoc.getPages().get(i);

    // Copy page from input to output
    Page outPage = outDoc.copyPage(inPage, copyOptions);

    if (i == 0)
    {
        // Add image on the first page
        addDatamatrix(outDoc, outPage, datamatrixPath);
    }

    // Add page to output document
    outDoc.getPages().add(outPage);

    // Cleanup 
    outPage.close();
    inPage.close();
}
private static void addDatamatrix(Document document, Page page, String datamatrixPath)
throws ErrorCodeException, FileNotFoundException
{
    ContentGenerator generator = null;

    try
    {
        // Create content generator 
        generator = new ContentGenerator(page.getContent(), false);

        // Import data matrix
        FileStream inMatrix = new FileStream(datamatrixPath, "r");

        // Create image object for data matrix
        Image datamatrix = document.createImage(inMatrix);

        // Data matrix size
        double datamatrixSize = 85;

        // Calculate Rectangle for data matrix
        Rectangle rect = new Rectangle(
                Border,
                page.getSize().height - (datamatrixSize + Border),
                datamatrixSize + Border,
                page.getSize().height - Border
                );

        // Paint image of data matrix into the specified rectangle
        generator.paintImage(datamatrix, rect);
    }
    finally
    {
        // Close content generator
        if (generator != null)
            generator.close();
    }
}

Add image to PDF

Place an image with a specified size at a specific location of a page.

l'exemple C# :
// Open input document 
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
{
    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata 
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Set copy options
    CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | 
        CopyOption.CopyFormFields | CopyOption.CopyOutlines | CopyOption.CopyLogicalStructure;

    // Loop through all pages of input
    for (int i = 1; i <= inDoc.Pages.Count; i++)
    {
        // Copy page from input to output
        using (Page inPage = inDoc.Pages[i - 1])
        using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
        {
            if (i == pageNumber)
            {
                // Add image on chosen page
                AddImage(outDoc, outPage, imagePath, 150, 150);
            }
            // Add page to output document 
            outDoc.Pages.Add(outPage);
        }
    }
}
private static void AddImage(Document document, Page page, string imagePath, double x, double y)
{
    // Create content generator 
    using (ContentGenerator generator = new ContentGenerator(page.Content, false))
    // Load image from input path
    using (Stream inImage = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
    // Create image object
    using (Image image = document.CreateImage(inImage))
    {
        double resolution = 150;

        // Calculate rectangle for image 
        Rectangle rect = new Rectangle
        {
            Left = x,
            Bottom = y,
            Right = x + image.Width * 72 / resolution,
            Top = y + image.Height * 72 / resolution
        };
        // Paint image into the specified rectangle 
        generator.PaintImage(image, rect);
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create output document
outStream = new FileStream(outPath, "rw");
outDoc = Document.create(outStream, Conformance.UNKNOWN, null);

// Set output intent
if (inDoc.getOutputIntent() != null)
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Copy metadata
Metadata metadata =  outDoc.copyMetadata(inDoc.getMetadata());
outDoc.setMetadata(metadata);

// Set copy options
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS,
        CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Loop through all pages of input
for (int i = 0; i < inDoc.getPages().size(); i ++)
{
    Page inPage = inDoc.getPages().get(i);

    // Copy page from input to output
    Page outPage = outDoc.copyPage(inPage, copyOptions);

    if (i == (pageNumber - 1))
    {
        // Add image on chosen page
        addImage(outDoc, outPage, imagePath, 150, 150);
    }

    // Add page to output document
    outDoc.getPages().add(outPage);

    // Cleanup
    outPage.close();
    inPage.close();
}
private static void addImage(Document document, Page outPage, String imagePath, double x, double y)
throws ErrorCodeException, IOException 
{
    FileStream inImage = null;
    Image image = null;
    ContentGenerator generator = null;

    try
    {
        // Create content generator 
        generator = new ContentGenerator(outPage.getContent(), false);

        // Load image from input path
        inImage = new FileStream(imagePath, "r");

        // Create image object
        image = document.createImage(inImage);

        double resolution = 150;

        // Calculate rectangle for image
        Rectangle rect = new Rectangle(
                x, 
                y, 
                x + image.getWidth() * 72 / resolution, 
                y + image.getHeight() * 72 / resolution
                );

        // Paint image into the specified rectangle
        generator.paintImage(image, rect);
    }
    finally
    {
        // Cleanup
        if (image != null)
            image.close();
        if (inImage != null)
            inImage.close();
        if (generator != null)
            generator.close();
    }
}

Add image mask to PDF

Place a rectangular image mask at a specified location of a page. The image mask is a stencil mask to fill or mask out the image per pixel.

l'exemple C# :
// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
{
    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Set copy options
    CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations |
        CopyOption.CopyFormFields | CopyOption.CopyOutlines | CopyOption.CopyLogicalStructure;

    // Get the device color space
    using (ColorSpace colorSpace = outDoc.CreateDeviceColorSpace(DeviceColorSpaceType.RGB))
    // Create paint object
    using (paint = outDoc.CreateSolidPaint(colorSpace, 1.0, 0.0, 0.0))
    {
        // Loop through all pages of input
        foreach (Page inPage in inDoc.Pages)
        {
            // Copy page from input to output
            using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
            {
                // Add image mask
                AddImageMask(outDoc, outPage, imageMaskPath, 250, 150);

                // Add page to document
                outDoc.Pages.Add(outPage);
            }
        }
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create output document
outStream = new FileStream(outPath, "rw");
outStream.setLength(0); 
outDoc = Document.create(outStream, Conformance.UNKNOWN, null);


// Set output intent
if (inDoc.getOutputIntent() != null)
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Copy metadata
outDoc.setMetadata(outDoc.copyMetadata(inDoc.getMetadata()));

// Set copy options
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS,
        CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Get the device color space
ColorSpace colorSpace = outDoc.createDeviceColorSpace(DeviceColorSpaceType.RGB);

// Create paint object
paint = outDoc.createSolidPaint(colorSpace, 1.0, 0.0, 0.0);

// Loop through all pages of input
for (Page inPage : inDoc.getPages())
{
    // Copy page from input to output
    Page outPage = outDoc.copyPage(inPage, copyOptions);

    // Add image mask 
    addImageMask(outDoc, outPage, imageMaskPath, 250, 150);

    // Add page to document
    outDoc.getPages().add(outPage);

    // Cleanup
    outPage.close();
    inPage.close();
}
private static void addImageMask(Document document, Page outPage, String imagePath, double x, double y)
throws ErrorCodeException, IOException 
{

    FileStream inImage = null;
    ImageMask imageMask = null;
    ContentGenerator generator = null;

    try
    {
        // Create content generator 
        generator = new ContentGenerator(outPage.getContent(), false);

        // Load image from input path
        inImage = new FileStream(imagePath, "r");

        // Create image mask object
        imageMask = document.createImageMask(inImage);

        double resolution = 150;

        // Calculate rectangle for image
        Rectangle rect = new Rectangle(
                x, 
                y, 
                x + imageMask.getWidth() * 72 / resolution,
                y + imageMask.getHeight() * 72 / resolution
                );

        // Paint image mask into the specified rectangle
        generator.paintImageMask(imageMask, rect, paint);
    }
    finally
    {
        // Cleanup
        if (imageMask != null)
            imageMask.close();
        if (inImage != null)
            inImage.close();
        if (generator != null)
            generator.close();
    }
}

Add stamp to PDF

Add a transparent stamp text onto each page of a PDF document. Optionally specify the color and the opacity of the stamp.

l'exemple C# :
// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
using (Font font = outDoc.CreateSystemFont("Arial", "Italic", true))
{
    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Set copy options
    CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | 
        CopyOption.CopyFormFields | CopyOption.CopyOutlines | CopyOption.CopyLogicalStructure;

    // Get the device color space
    using (ColorSpace colorspace = outDoc.CreateDeviceColorSpace(DeviceColorSpaceType.RGB))
    // Create paint object with the choosen RGB color
    using (paint = outDoc.CreateAlphaPaint(colorspace, alpha, 1.0, 0.0, 0.0))
    {
        // Loop through all pages of input
        foreach (Page inPage in inDoc.Pages)
        {
            // Copy page from input to output
            using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
            {
                // Add text to page
                AddStamp(outDoc, outPage, stampString, font, 50);

                // Add page to document
                outDoc.Pages.Add(outPage);
            }
        }
    }
}
private static void AddStamp(Document outputDoc, Page outPage, string stampString, 
    Font font, double fontSize)
{
    // Create content generator and text object
    using (ContentGenerator gen = new ContentGenerator(outPage.Content, false))
    using (Text text = outputDoc.CreateText())
    {
        // Create text generator
        using (TextGenerator textgenerator = new TextGenerator(text, font, fontSize, null))
        {
            // Calculate point and angle of rotation
            Point rotationCenter = new Point
            {
                X = outPage.Size.Width / 2.0,
                Y = outPage.Size.Height / 2.0
            };
            double rotationAngle = Math.Atan2(outPage.Size.Height,
                outPage.Size.Width) / Math.PI * 180.0;

            // Rotate textinput around the calculated position
            Transformation trans = new Transformation();
            trans.RotateAround(rotationAngle, rotationCenter);
            gen.Transform(trans);

            // Calculate position
            Point position = new Point
            {
                X = (outPage.Size.Width - textgenerator.GetWidth(stampString)) / 2.0,
                Y = (outPage.Size.Height - font.Ascent * fontSize) / 2.0
            };

            // Move to position
            textgenerator.MoveTo(position);
            // Set text rendering 
            textgenerator.SetRendering(paint, null, false);
            // Add given stamp string
            textgenerator.ShowLine(stampString);
        }
        // Paint the positioned text
        gen.PaintText(text);
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create output document
outStream = new FileStream(outPath, "rw");
outStream.setLength(0); 
outDoc = Document.create(outStream, Conformance.UNKNOWN, null);

// Create embedded font in output document
Font font = outDoc.createSystemFont("Arial", "Italic", true);

// Set output intent
if (inDoc.getOutputIntent() != null) 
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Copy metadata
Metadata metadata =  outDoc.copyMetadata(inDoc.getMetadata());
outDoc.setMetadata(metadata);

// Set copy options
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS,
        CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Get the device color space
ColorSpace colorSpace = outDoc.createDeviceColorSpace(DeviceColorSpaceType.RGB);

// Choose the RGB color value
double[] color = {1.0, 0.0, 0.0};

// Create paint object
paint = outDoc.createAlphaPaint(colorSpace, alpha, color);

// Loop throw all pages of input
for (Page inPage : inDoc.getPages())
{
    // Copy page from input to output
    Page outPage = outDoc.copyPage(inPage, copyOptions);

    // Add text to page 
    addStamp(outDoc, outPage, stampString, font, 50);

    // Add page to document
    outDoc.getPages().add(outPage);

    //Cleanup
    outPage.close();
    inPage.close();
}
private static void addStamp(Document outputDoc, Page outPage, String stampString, 
Font font, double fontSize) throws ErrorCodeException 
{

    ContentGenerator generator = null;

    try 
    {
        // Create content generator 
        generator = new ContentGenerator(outPage.getContent(), false);

        // Create text object
        Text text = outputDoc.createText();

        // Create text generator
        TextGenerator textgenerator = new TextGenerator(text, font, fontSize, null);

        // Calculate point and angle of rotation
        Point rotationCenter = new Point(
                outPage.getSize().width / 2.0,
                outPage.getSize().height / 2.0
                );

        // Calculate rotation angle
        double rotationAngle = Math.atan2(outPage.getSize().height, 
            outPage.getSize().width) / Math.PI * 180.0;

        // Rotate text input around the calculated position
        Transformation trans = new Transformation();
        trans.rotateAround(rotationAngle, rotationCenter);
        generator.transform(trans);

        // Calculate position 
        Point position = new Point(
                (outPage.getSize().width - textgenerator.getWidth(stampString)) / 2.0,
                (outPage.getSize().height - font.getAscent() * fontSize) / 2.0
                );

        // Move to position 
        textgenerator.moveTo(position);

        // Set text rendering 
        textgenerator.setRendering(paint, null, false);

        // Add given stamp string 
        textgenerator.showLine(stampString);
        textgenerator.close(); 

        // Paint the positioned text
        generator.paintText(text);
    } 
    finally
    {
        // Close content generator
        if (generator != null)
            generator.close();
    }
}

Add text to PDF

Add text at a specified position on the first page of a PDF document.

l'exemple C# :
// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, inDoc.Conformance, null))
using (Font font = outDoc.CreateSystemFont("Arial", "Italic", true))
{
    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata 
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Set copy options
    CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | 
        CopyOption.CopyFormFields | CopyOption.CopyOutlines | CopyOption.CopyLogicalStructure;

    // Loop through all pages of input
    for (int i = 0; i < inDoc.Pages.Count; i++)
    {
        // Copy page from input to output
        using (Page inPage = inDoc.Pages[i])
        using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
        {
            if (i == 0)
            {
                // Add text on first page
                AddText(outDoc, outPage, textString, font, 15);
            }
            // Add page to document
            outDoc.Pages.Add(outPage);
        }
    }
}
private static void AddText(Document outputDoc, Page outPage, string textString, Font font,
    double fontSize)
{
    // Create content generator and text object
    using (ContentGenerator gen = new ContentGenerator(outPage.Content, false))
    using (Text text = outputDoc.CreateText())
    {
        // Create text generator
        using (TextGenerator textGenerator = new TextGenerator(text, font, fontSize, null))
        {
            // Calculate position
            Point position = new Point
            {
                X = Border,
                Y = outPage.Size.Height - Border - fontSize * font.Ascent
            };

            // Move to position
            textGenerator.MoveTo(position);
            // Add given text string
            textGenerator.ShowLine(textString);
        }
        // Paint the positioned text
        gen.PaintText(text);
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create output document
outStream = new FileStream(outPath, "rw");
outStream.setLength(0);
outDoc = Document.create(outStream, inDoc.getConformance(), null);

// Create embedded font in output document
Font font = outDoc.createSystemFont("Arial", "Italic", true);

// Set output intent
if (inDoc.getOutputIntent() != null) 
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Copy metadata
Metadata metadata =  outDoc.copyMetadata(inDoc.getMetadata());
outDoc.setMetadata(metadata);

// Set copy options 
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS,
        CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Loop through all pages of input
for (int i = 0; i < inDoc.getPages().size(); i ++)
{
    Page inPage = inDoc.getPages().get(i);

    // Copy page from input to output
    Page outPage = outDoc.copyPage(inPage, copyOptions);

    if (i == 0)
    {
        // Add text on first page
        addText(outDoc, outPage, textString, font, 15);
    }

    // Add page to output document
    outDoc.getPages().add(outPage);

    // Cleanup 
    outPage.close();
    inPage.close();
}
private static void addText(Document outputDoc, Page outPage, String textString, Font font,
double fontSize) throws ErrorCodeException 
{

    ContentGenerator generator = null;

    try 
    {
        // Create content generator 
        generator = new ContentGenerator(outPage.getContent(), false);

        // Create text object
        Text text = outputDoc.createText();

        // Create a text generator
        TextGenerator textgenerator = new TextGenerator(text, font, fontSize, null);

        // Calculate position
        Point position = new Point(
                Border,
                outPage.getSize().height - Border - fontSize * font.getAscent()
                );

        // Move to position
        textgenerator.moveTo(position);
        // Add given text string
        textgenerator.showLine(textString);
        // Close text generator
        textgenerator.close();

        // Paint the positioned text
        generator.paintText(text);
    } 
    finally 
    {
        // Close content generator
        if (generator != null)
            generator.close();
    }
}

Layout text of PDF

Create a new PDF document with one page. On this page, within a given rectangular area, add a text block with a full justification layout.

l'exemple C# :
// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.CreateNew, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
using (Font font = outDoc.CreateSystemFont("Arial", "Italic", true))
{
    // Create page
    using (Page outPage = outDoc.CreatePage(PageSize))
    {
        // Add text as justified text
        LayoutText(outDoc, outPage, textPath, font, 20);

        // Add page to document
        outDoc.Pages.Add(outPage);
    }
}
private static void LayoutText(Document outputDoc, Page outPage, string textPath, Font font,
    double fontSize)
{
    // Create content generator 
    using (ContentGenerator gen = new ContentGenerator(outPage.Content, false))
    {
        // Create text object
        using (Text text = outputDoc.CreateText())
        {
            // Create text generator
            using (TextGenerator textGenerator = new TextGenerator(text, font, fontSize, null))
            {
                string[] lines = File.ReadAllLines(textPath, Encoding.Default);

                // Calculate position
                Point position = new Point
                {
                    X = Border,
                    Y = outPage.Size.Height - Border
                };

                // Move to position
                textGenerator.MoveTo(position);

                // Loop throw all lines of the textinput
                foreach (string line in lines)
                {
                    // Split string in substrings
                    string[] substrings = line.Split(new char[] { ' ' }, StringSplitOptions.None);
                    string currentLine = null;
                    double maxWidth = (outPage.Size.Width - (Border * 2));
                    int wordcount = 0;

                    // Loop throw all words of input strings
                    foreach (string word in substrings)
                    {
                        string tempLine;

                        // Concatenate substrings to line
                        if (currentLine != null)
                        {
                            tempLine = currentLine + " " + word;
                        }
                        else
                        {
                            tempLine = word;
                        }

                        // Calculate the current width of line
                        double width = textGenerator.GetWidth(currentLine);
                        if ((textGenerator.GetWidth(tempLine) > maxWidth))
                        {
                            // Calculate the word spacing
                            textGenerator.WordSpacing = ((maxWidth - width) / (wordcount - 1));
                            // Paint on new line
                            textGenerator.ShowLine(currentLine);
                            textGenerator.WordSpacing = (0);
                            currentLine = word;
                            wordcount = 1;
                        }
                        else
                        {
                            currentLine = tempLine;
                            wordcount++;
                        }
                    }
                    textGenerator.WordSpacing = (0);
                    // Add given stamp string
                    textGenerator.ShowLine(currentLine);
                }
                // Paint the positioned text
                gen.PaintText(text);
            }
        }
    }
}
l'exemple Java :
// Create output document
outStream = new FileStream(outPath, "rw");
outStream.setLength(0);
outDoc = Document.create(outStream, Conformance.UNKNOWN, null);

// Create embedded font in output document
Font font = outDoc.createSystemFont("Arial", "Italic", true);

// Create page 
Page outPage = outDoc.createPage(PageSize);

// Add text to document
layoutText(outDoc, outPage, textPath, font, 20);

// Add page to output document
outDoc.getPages().add(outPage);

// Cleanup 
outPage.close();
private static void layoutText(Document outputDoc, Page outPage, String textPath, Font font,
    double fontSize) throws ErrorCodeException  
{

    ContentGenerator generator = null;

    try 
    {
        // Create content generator 
        generator = new ContentGenerator(outPage.getContent(), false);

        // Create text object
        Text text = outputDoc.createText();

        // Create a text generator
        TextGenerator textGenerator = new TextGenerator(text, font, fontSize, null);

        try 
        {
            List<String> lines = Files.readAllLines(Paths.get(textPath), Charset.defaultCharset());

            // Calculate position
            Point position = new Point(
                    Border,
                    outPage.getSize().height - Border
                    );

            // Move to position
            textGenerator.moveTo(position);

            // Loop throw all lines of the textinput
            for (String line : lines)
            {
                // Split string in substrings
                String[] substrings = line.split(" ");
                String currentLine = null;
                double maxWidth = (outPage.getSize().width - (Border * 2));

                int wordCount = 0;

                // Loop throw all words of input strings
                for (String word : substrings)
                {
                    String tempLine;

                    // Concatenate substrings to line
                    if (currentLine != null)
                    {
                        tempLine = currentLine + " " + word;
                    }
                    else
                    {
                        tempLine = word;
                    }

                    // Calculate the current width of line 
                    double width = textGenerator.getWidth(currentLine);

                    if ((textGenerator.getWidth(tempLine) > maxWidth))
                    {
                        // Calculate the word spacing
                        textGenerator.setWordSpacing((maxWidth - width) / (double)(wordCount - 1));

                        // Paint on new line
                        textGenerator.showLine(currentLine);
                        textGenerator.setWordSpacing(0);
                        currentLine = word;
                        wordCount = 1;
                    }
                    else
                    {
                        currentLine = tempLine;
                        wordCount++;
                    }
                }
                textGenerator.setWordSpacing(0);
                // Add given stamp string 
                textGenerator.showLine(currentLine);
            }
            // Paint the positioned text
            generator.paintText(text);

            // Close text generator
            textGenerator.close();
        }
        catch (Exception e) 
        {
            e.printStackTrace();
            System.exit(-1);
        } 
    }
    finally 
    {
        // Cleanup
        if (generator != null)
            generator.close();
    }
}

Stamp page number to PDF

Stamp the page number to the footer of each page of a PDF document.

l'exemple C# :
// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, inDoc.Conformance, null))
{
    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Set copy options 
    CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | 
        CopyOption.CopyFormFields | CopyOption.CopyOutlines | CopyOption.CopyLogicalStructure;

    int pageNo = 1;

    // Create embedded font in output document 
    using (Font font = outDoc.CreateSystemFont("Arial", string.Empty, true))
    {
        // Loop through all pages of input
        foreach (Page inPage in inDoc.Pages)
        {
            // Copy page from input to output
            using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
            {
                // Stamp page number on current page of output document
                AddPageNumber(outDoc, outPage, font, pageNo++);

                // Add page to output document
                outDoc.Pages.Add(outPage);
            }
        }
    }
}
private static void AddPageNumber(Document outDoc, Page outPage, Font font, int pageNumber)
{
    // Create content generator
    using (ContentGenerator generator = new ContentGenerator(outPage.Content, false))
    // Create text object
    using (Text text = outDoc.CreateText())
    {
        // Create a text generator with the given font, size and position
        using (TextGenerator textgenerator = new TextGenerator(text, font, 8, null))
        {
            // Generate string to be stamped as page number
            string stampText = string.Format("Page {0}", pageNumber);

            // Calculate position for centering text at bottom of page
            Point position = new Point
            {
                X = (outPage.Size.Width / 2) - (textgenerator.GetWidth(stampText) / 2),
                Y = 10
            };

            // Position the text
            textgenerator.MoveTo(position);
            // Add page number
            textgenerator.Show(stampText);
        }
        // Paint the positioned text
        generator.PaintText(text);
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create output document
outStream = new FileStream(outPath, "rw");
outDoc = Document.create(outStream, inDoc.getConformance(), null);

// Set output intent
if (inDoc.getOutputIntent() != null)
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Copy metadata
Metadata metadata =  outDoc.copyMetadata(inDoc.getMetadata());
outDoc.setMetadata(metadata);

// Set copy options
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS,
        CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Copy pages from input to output
int pageNo = 1;

// Create embedded font in output document
Font font = outDoc.createSystemFont("Arial", "", true);

// Loop through all pages of input
for (Page inPage : inDoc.getPages()) 
{
    // Copy page from input to output
    Page outPage = outDoc.copyPage(inPage, copyOptions);

    // Stamp page number on current page of output document
    applyStamps(outDoc, outPage, font, pageNo++);

    // Add page to output document
    outDoc.getPages().add(outPage);

    // Cleanup
    outPage.close();
    inPage.close();
}
private static void applyStamps(Document doc, Page page, Font font, int pageNo) 
    throws ErrorCodeException 
{

    ContentGenerator generator = null;

    try 
    {
        // Create content generator 
        generator = new ContentGenerator(page.getContent(), false);

        // Create text object
        Text text = doc.createText();

        // Create a text generator with the given font, size and position
        TextGenerator textgenerator = new TextGenerator(text, font, 8, null);

        // Generate string to be stamped as page number
        String stampText = String.format("Page %d", pageNo);

        // Calculate position for centering text at bottom of page
        Point position = new Point(
                (page.getSize().width / 2) - (textgenerator.getWidth(stampText) / 2),
                10
                );

        // Position the text
        textgenerator.moveTo(position);
        // Add page number
        textgenerator.show(stampText);
        // Close text generator
        textgenerator.close();

        // Paint the positioned text
        generator.paintText(text);
    }
    finally 
    {
        // Close content generator
        if (generator != null)
            generator.close();
    }
}

Document Setup

Add metadata to PDF

Specify metadata, like author, title and creator of a PDF document. Optionally use the metadata of another PDF document or the content of an XMP file.

l'exemple C# :
// Open input document 
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, inDoc.Conformance, null))
{
    // Copy output intent
    using (ColorSpace inIntent = inDoc.OutputIntent)
    {
        if (inIntent != null)
        {
            using (ColorSpace outputIntent = outDoc.CopyColorSpace(inIntent))
                outDoc.OutputIntent = outputIntent;
        }
    }

    // Set copy options
    CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | 
        CopyOption.CopyFormFields | CopyOption.CopyOutlines | CopyOption.CopyLogicalStructure;

    // Copy pages from input document
    foreach (Page inPage in inDoc.Pages)
    {
        Page outPage = outDoc.CopyPage(inPage, copyOptions);

        outDoc.Pages.Add(outPage);
    }

    if (args.Length == 3)
    {
        Metadata mdata;

        // Add metadata from a input file 
        using (FileStream metaStream = File.OpenRead(mdatafile))
        {
            if (mdatafile.EndsWith(".pdf"))
            {
                // Use the metadata of another PDF file
                Document metaDoc = Document.Open(metaStream, "");
                mdata = outDoc.CopyMetadata(metaDoc.Metadata);
            }
            else
            {
                // Use the content of an XMP metadata file 
                mdata = outDoc.CreateMetadata(metaStream);
            }
            outDoc.Metadata = mdata;
        }
    }
    else
    {
        // Set some metadata properties 
        Metadata metadata = outDoc.Metadata;
        metadata.Author = "Your Author";
        metadata.Title = "Your Title";
        metadata.Subject = "Your Subject";
        metadata.Creator = "Your Creator";
        metadata.Producer = "Your Producer";
    }
}
l'exemple Java :
// Open input document 
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create output document 
outStream = new FileStream(outPath, "rw");
outStream.setLength(0); 
outDoc = Document.create(outStream, inDoc.getConformance(), null);

// Copy output intent
if (inDoc.getOutputIntent() != null)
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Set copy options
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS,
        CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Loop through all pages of input
for (Page inPage : inDoc.getPages()) 
{
    // Copy page from input to output
    Page outPage = outDoc.copyPage(inPage, copyOptions);

    // Add pages to output document
    outDoc.getPages().add(outPage);

    // Cleanup
    outPage.close();
    inPage.close();
}

if (args.length == 3)
{
    Metadata mdata;

    // Add metadata from a input file 
    FileStream metaStream = new FileStream(mdatafile, "r");

    if (mdatafile.toLowerCase().endsWith(".pdf"))
    {
        // Use the metadata of another PDF file
        Document metaDoc = Document.open(metaStream, null);
        mdata = outDoc.copyMetadata(metaDoc.getMetadata());
    }
    else
    {
        // Use the content of an XMP metadata file
        mdata = outDoc.createMetadata(metaStream);
    }
    outDoc.setMetadata(mdata);
}
else
{
    // Set some metadata properties
    Metadata metadata = outDoc.getMetadata();
    metadata.setAuthor("Your Author");
    metadata.setTitle("Your Title");
    metadata.setSubject("Your Subject");
    metadata.setCreator("Your Creator");
    metadata.setProducer("Your Producer");
}

Encrypt PDF

Encrypt a PDF document with a user password and an owner password. When opening the document, either of the passwords must be provided. If providing the user password, the document can be viewed and printed only. Providing the owner password grants full access to the document.

l'exemple C# :
// Create encryption parameters
EncryptionParams encryptionParams = new EncryptionParams(UserPwd, OwnerPwd, Permission.Print | 
    Permission.DigitalPrint);

// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create output document and set a user and owner password
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, encryptionParams))
{
    // Set copy options
    CopyOption copyOptions = CopyOption.CopyOutlines | CopyOption.CopyLinks | 
        CopyOption.CopyAnnotations | CopyOption.CopyFormFields | CopyOption.CopyLogicalStructure;

    // Copy metadata
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Loop through all pages of input
    foreach (Page inPage in inDoc.Pages)
    {
        // Copy from input to output
        using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
        {
            // Add pages to first document 
            outDoc.Pages.Add(outPage);
        }
    }
}
l'exemple Java :
// Create encryption parameters
EncryptionParams encryptionParams = new EncryptionParams(userPwd, ownerPwd, EnumSet.of(Permission.PRINT , Permission.DIGITAL_PRINT));

// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create output document and set a user and owner password
outStream = new FileStream(outPath, "rw");
outStream.setLength(0);
outDoc = Document.create(outStream, Conformance.UNKNOWN, encryptionParams);

// Set copy options
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_OUTLINES, CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS, CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Copy metadata
outDoc.setMetadata(outDoc.copyMetadata(inDoc.getMetadata()));

// Loop through all pages of input
for (Page inPage : inDoc.getPages())
{
    // Copy from input to output
    Page outPage = outDoc.copyPage(inPage, copyOptions);

    // Add pages to first document
    outDoc.getPages().add(outPage);

    // Cleanup
    if (outPage != null)
        outPage.close();
    if (inPage != null)
        inPage.close();
}

Flatten form fields in PDF

Flatten the visual appearance of form fields and discard all interactive elements.

l'exemple C# :
// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
{
    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata 
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Set copy options and flatten form fields
    CopyOption copyOptions = CopyOption.CopyOutlines | CopyOption.CopyLinks | 
        CopyOption.FlattenFormFields | CopyOption.CopyLogicalStructure;

    // Loop through all pages of input
    for (int i = 0; i < inDoc.Pages.Count; i++)
    {
        // Copy page from input to output
        using (Page inPage = inDoc.Pages[i])
        using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
        {
            // Add pages to document
            outDoc.Pages.Add(outPage);
        }

    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create output document
outStream = new FileStream(outPath, "rw");
outStream.setLength(0);
outDoc = Document.create(outStream, Conformance.UNKNOWN, null);

// Set output intent
if (inDoc.getOutputIntent() != null)
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Copy metadata
outDoc.setMetadata(outDoc.copyMetadata(inDoc.getMetadata())); 

// Set copy options and flatten annotations, form fields and signatures
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_OUTLINES, CopyOption.COPY_LINKS, CopyOption.FLATTEN_FORM_FIELDS, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Loop through all pages of input
for (int i = 0; i < inDoc.getPages().size(); i++)
{
    Page inPage = inDoc.getPages().get(i);

    // Copy page from input to output
    Page outPage = outDoc.copyPage(inPage, copyOptions);

    // Add pages to document
    outDoc.getPages().add(outPage);

    // Cleanup
    if (outPage != null)
        outPage.close();
    if (inPage != null)
        inPage.close();
}

Merge multiple PDFs

Merge several PDF documents to one.

l'exemple C# :
// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
{
    // Merge input documents 
    for (int i = 0; i < args.Length - 1; i++)
    {
        // Open input document
        using (Stream inFs = new FileStream(inPath[i], FileMode.Open, FileAccess.Read))
        using (Document inDoc = Document.Open(inFs, null))
        {
            // Set copy options
            CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | 
                CopyOption.FlattenFormFields | CopyOption.CopyOutlines | 
                CopyOption.OptimizeResources | CopyOption.CopyLogicalStructure;

            // Copy pages of input 
            foreach (Page inPage in inDoc.Pages)
            {
                // Copy page from input to output
                using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
                {
                    // Add pages to document
                    outDoc.Pages.Add(outPage);
                }
            }
        }
    }
}
l'exemple Java :
// Create output document
outStream = new FileStream(outPath, "rw");
outStream.setLength(0);
outDoc = Document.create(outStream, Conformance.UNKNOWN, null);

// Merge input document
for (int i = 0; i < args.length - 1; i++)
{
    Document inDoc = null;
    FileStream inStream = null;

    try
    {
        // Open input document 
        inStream = new FileStream(inPath[i], "r");
        inDoc = Document.open(inStream, null);

        // Set copy options
        EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, 
        CopyOption.COPY_ANNOTATIONS, CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, 
        CopyOption.OPTIMIZE_RESOURCES, CopyOption.COPY_LOGIGAL_STRUCTURE);

        // Copy pages of input
        for (Page inPage : inDoc.getPages()) 
        {
            // Copy page from input to output
            Page outPage = outDoc.copyPage(inPage, copyOptions);

            // Add pages to output document
            outDoc.getPages().add(outPage);

            // Clean up
            outPage.close();
            inPage.close();
        }
    }
    finally
    {
        // Close input document
        if (inDoc != null)
            inDoc.close();
        if (inStream != null)
            inStream.close();
    }
}

Overlay color of PDF

Overlay all pages of a PDF document with a specified color.

l'exemple C# :
// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create output document
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
{

    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Set blendmode
    BlendMode blendMode = BlendMode.Multiply;

    // Create colorspace
    using (ColorSpace colorSpace = outDoc.CreateDeviceColorSpace(colorType))
    {
        Paint paint = null;
        switch (colorType)
        {
            // Create blending paint
            case DeviceColorSpaceType.Gray:
                paint = outDoc.CreateBlendingPaint(colorSpace, blendMode, colorAlpha, color[0]);
                break;
            case DeviceColorSpaceType.RGB:
                paint = outDoc.CreateBlendingPaint(colorSpace, blendMode, colorAlpha, color[0],
                    color[1], color[2]);
                break;
            case DeviceColorSpaceType.CMYK:
                paint = outDoc.CreateBlendingPaint(colorSpace, blendMode, colorAlpha, color[0],
                    color[1], color[2], color[3]);
                break;
        }

        // Get output pages
        PageList outPages = outDoc.Pages;

        // Set copy options
        CopyOption copyOptions = CopyOption.CopyAnnotations | CopyOption.CopyFormFields |
            CopyOption.CopyOutlines | CopyOption.CopyLinks | CopyOption.CopyLogicalStructure;

        // Loop through all pages
        foreach (Page inPage in inDoc.Pages)
        {
            // Create a new page
            Size size = inPage.Size;
            using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
            {
                // Create a content generator
                using (ContentGenerator generator = new ContentGenerator(outPage.Content, false))
                {
                    // Calculate Rectangle
                    Rectangle rect = new Rectangle
                    {
                        Left = 0,
                        Bottom = 0,
                        Right = size.Width,
                        Top = size.Height
                    };

                    // Make a rectangular path the same size as the page
                    using (PdfTools.Pdf.Path path = new PdfTools.Pdf.Path(InsideRule.EvenOdd))
                    {
                        using (PathGenerator pathGenerator = new PathGenerator(path))
                        {
                            Rectangle pathRect = new Rectangle
                            {
                                Left = 0,
                                Bottom = 0,
                                Right = size.Width,
                                Top = size.Height
                            };
                            pathGenerator.AddRectangle(pathRect);
                        }
                        // Paint the path with the transparent paint
                        generator.PaintPath(path, paint, null, false);
                    }
                }
                // Add pages to output document
                outPages.Add(outPage);
            }
        }
    }
}
l'exemple Java :
    try
    {
        // Open input document
        inStream = new FileStream(inPath, "r");
        inDoc = Document.open(inStream, null);

        try
        {
            // Create output document
            outStream = new FileStream(outPath, "rw");
            outStream.setLength(0);
            outDoc = Document.create(outStream, Conformance.UNKNOWN, null);

            // Set output intent 
            if (inDoc.getOutputIntent() != null)
                outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

            // Copy metadata
            outDoc.setMetadata(outDoc.copyMetadata(inDoc.getMetadata()));

            // Set blendmode 
            BlendMode blendMode = BlendMode.MULTIPLY;

            // Create colorspace
            ColorSpace colorSpace = outDoc.createDeviceColorSpace(colorType);

            // Create a transparent paint for the given color
            Paint paint = null;
            switch (colorType)
            {
            case GRAY:
                paint = outDoc.createBlendingPaint(colorSpace, blendMode, colorAlpha, color[0]);
                break;
            case RGB:
                paint = outDoc.createBlendingPaint(colorSpace, blendMode, colorAlpha, color[0], color[1], color[2]);
                break;
            case CMYK:
                paint = outDoc.createBlendingPaint(colorSpace, blendMode, colorAlpha, color[0], color[1], color[2], color[3]);
                break;
            }

            // Get output pages
            PageList outPages = outDoc.getPages();

            // Set copy options
            EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS,
                    CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, CopyOption.COPY_LOGIGAL_STRUCTURE);

            // Loop through all pages
            for (Page inPage : inDoc.getPages())
            {
                // Create a new page
                Size size = inPage.getSize();
                Page outPage = outDoc.copyPage(inPage, copyOptions);

                // Create a content generator
                ContentGenerator generator = new ContentGenerator(outPage.getContent(), false);

                try
                {
                    // Calculate rectangle
                    Rectangle rect = new Rectangle(
                            0,
                            0,
                            size.width,
                            size.height
                            );

                    // Make a rectangular path the same size as the page
                    Path path = new Path(InsideRule.EVEN_ODD);
                    PathGenerator pathGenerator = new PathGenerator(path);

                    pathGenerator.addRectangle(rect);

                    // Close path generator 
                    pathGenerator.close();

                    // Paint the path with the transparent paint
                    generator.paintPath(path, paint, null, false);
                }
                finally
                {
                    // Close content generator
                    if (generator != null)
                        generator.close();
                }

                // Add pages to output document
                outPages.add(outPage);

                // Cleanup
                outPage.close();
                inPage.close();
            }
        }
        finally
        {
            try
            {
                // Close output document
                if (outDoc != null)
                    outDoc.close();
                if (outStream != null)
                    outStream.close();
            }
            catch (ErrorCodeException e)
            {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }
    finally
    {
        try
        {
            // Close input document
            if (inDoc != null)
                inDoc.close();
            if (inStream != null)
                   inStream.close();
        }
        catch (ErrorCodeException e)
        {
            e.printStackTrace();
            System.exit(-1);
        }
    }
}
catch (Exception e)
{
    e.printStackTrace();
    System.exit(-1);
}

Remove pages from PDF

Selectively remove pages from a PDF document.

l'exemple C# :
// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))
{
    firstPage = Math.Max(Math.Min(inDoc.Pages.Count - 1, firstPage), 0);
    lastPage = Math.Max(Math.Min(inDoc.Pages.Count - 1, lastPage), 0);
    if (firstPage > lastPage)
    {
        Console.WriteLine("lastPage must be greater or equal to firstPage");
        return;
    }

    // Create output document
    using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
    using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
    {
        // Set copy options
        CopyOption copyOptions = CopyOption.CopyOutlines | CopyOption.CopyLinks | 
            CopyOption.CopyAnnotations | CopyOption.CopyFormFields |
            CopyOption.CopyLogicalStructure;

        // Set output intent
        if (inDoc.OutputIntent != null)
            using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
                outDoc.OutputIntent = outputIntent;

        // Copy metadata
        using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
            outDoc.Metadata = metadata;

        // Loop through all pages of input
        for (int i = 0; i < inDoc.Pages.Count; i++)
        {
            if (i >= firstPage && i <= lastPage)
            {
                // Copy from input to output
                using (Page inPage = inDoc.Pages[i])
                using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
                {
                    // Add pages to first document 
                    outDoc.Pages.Add(outPage);
                }
            }
        }
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

firstPage = Math.max(Math.min(inDoc.getPages().size() - 1, firstPage), 0);
lastPage = Math.max(Math.min(inDoc.getPages().size() - 1, lastPage), 0);
if (firstPage > lastPage)
{
    System.out.println("lastPage must be greater or equal to firstPage");
    return;
}

// Create output document
outStream = new FileStream(outPath, "rw");
outStream.setLength(0);
outDoc = Document.create(outStream, Conformance.UNKNOWN, null);

// Set copy options
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_OUTLINES, CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS, CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Set output intent
if (inDoc.getOutputIntent() != null)
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Copy metadata
outDoc.setMetadata(outDoc.copyMetadata(inDoc.getMetadata()));

// Loop through all pages of input
for (int i = 0; i <= inDoc.getPages().size(); i++)
{
    if (i >= firstPage && i <= lastPage)
    {
        Page inPage = inDoc.getPages().get(i);

        // Copy from input to output
        Page outPage = outDoc.copyPage(inPage, copyOptions);

        // Add pages to first document
        outDoc.getPages().add(outPage);

        // Cleanup
        if (outPage != null)
            outPage.close();
        if (inPage != null)
            inPage.close();
    }
}

Imposition

Create a booklet from PDF

Place up to two A4 pages in the right order on an A3 page, so that duplex printing and folding the A3 pages results in a booklet.

l'exemple C# :
// Open input document
Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read);
Document inDoc = Document.Open(inStream, null);

// Create output document 
Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite);
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
using (Font font = outDoc.CreateSystemFont("Arial", "Italic", true))
{
    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Copy pages
    PageList inPages = inDoc.Pages;
    PageList outPages = outDoc.Pages;
    int numberOfSheets = (inPages.Count + 3) / 4;

    for (int sheetNumber = 0; sheetNumber < numberOfSheets; ++sheetNumber)
    {

        // Add on front side
        CreateBooklet(inPages, outDoc, outPages, 4 * numberOfSheets - 2 * sheetNumber - 1,
            2 * sheetNumber, font);

        // Add on back side
        CreateBooklet(inPages, outDoc, outPages, 2 * sheetNumber + 1, 
            4 * numberOfSheets - 2 * sheetNumber - 2, font);
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create output document
outStream = new FileStream(outPath, "rw");
outStream.setLength(0);
outDoc = Document.create(outStream, Conformance.UNKNOWN, null);
Font font = outDoc.createSystemFont("Arial", "Italic", true);

// Set output intent
if (inDoc.getOutputIntent() != null)
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Copy metadata
outDoc.setMetadata(outDoc.copyMetadata(inDoc.getMetadata()));

// Copy pages
inPages = inDoc.getPages();
outPages = outDoc.getPages();
int numberOfSheets = (inPages.size() + 3) / 4;

for (int sheetNumber = 0; sheetNumber < numberOfSheets; ++sheetNumber)
{
    // Add on front side
    CreateBooklet(inPages, outDoc, outPages, 4 * numberOfSheets - 2 * sheetNumber - 1, 2 * sheetNumber, font);

    // Add on back side
    CreateBooklet(inPages, outDoc, outPages, 2 * sheetNumber + 1, 4 * numberOfSheets - 2 * sheetNumber - 2, font);
}
private static void CreateBooklet(PageList inPages, Document outDoc, PageList outPages, int leftPageIndex, int rightPageIndex, Font font) throws ErrorCodeException
{
    // Set copy options
    EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS,
          CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, CopyOption.COPY_LOGIGAL_STRUCTURE);

    // Create page object
    Page outPage = outDoc.createPage(PageSize);

    // Create content generator
    ContentGenerator generator = new ContentGenerator(outPage.getContent(), false);
    try
    {
        BlendMode blendMode = BlendMode.NORMAL;
        double alpha = 1.0;
        TransparencyParams transparencyParams = new TransparencyParams(blendMode, alpha);

        // Left page
        if (leftPageIndex < inPages.size())
        {
            Page leftPage = inPages.get(leftPageIndex);

            // Copy page from input to output
            Group leftGroup = outDoc.copyPageAsGroup(leftPage, copyOptions);

            // Paint group on the calculated rectangle
            generator.paintGroup(leftGroup, ComputTargetRect(leftGroup.getSize(), true), transparencyParams);

            // Add page number to page
            StampPageNumber(outDoc, font, generator, leftPageIndex + 1, true);
        }

        // Right page
        if (rightPageIndex < inPages.size())
        {
            Page rightPage = inPages.get(rightPageIndex);

            // Copy page from input to output
            Group rightGroup = outDoc.copyPageAsGroup(rightPage, copyOptions);

            // Paint group on the calculated rectangle 
            generator.paintGroup(rightGroup, ComputTargetRect(rightGroup.getSize(), false), transparencyParams);

            // Add page number to page
            StampPageNumber(outDoc, font, generator, rightPageIndex + 1, false);
        }
    }
    finally
    {
        if (generator != null)
            generator.close();
    }

    // Add page to output document
    outPages.add(outPage);
    outPage.close();
}
private static Rectangle ComputTargetRect(Size bbox, Boolean isLeftPage)
{
    // Calculate factor for fitting page into rectangle
    double scale = Math.min(CellWidth / bbox.width, CellHeight / bbox.height);
    double groupWidth = bbox.width * scale; 
    double groupHeight = bbox.height * scale;

    // Calculate x-value
    double groupXPos;
    if (isLeftPage)
        groupXPos = CellLeft + (CellWidth - groupWidth) / 2;
    else
        groupXPos = CellRight + (CellWidth - groupWidth) / 2;

    // Calculate y-value
    double groupYPos = CellYPos + (CellHeight - groupHeight) / 2;

    // Calculate rectangle
    return new Rectangle(
            groupXPos,
            groupYPos,
            groupXPos + groupWidth,
            groupYPos + groupHeight
            );
}
private static void StampPageNumber(Document document, Font font, ContentGenerator generator, int pageNo, boolean isLeftPage) throws ErrorCodeException
{
    // Create text object 
    Text text = document.createText();

    // Create text generator
    TextGenerator textgenerator = new TextGenerator(text, font, 8, null);

    try
    {
        String stampText = String.format("Page %d", pageNo);

        // Get width of stamp text
        double width = textgenerator.getWidth(stampText);
        double x;

        // Calculate position 
        if (isLeftPage)
            x = Border + 0.5 * CellWidth - width / 2;
        else
            x = 2 * Border + 1.5 * CellWidth - width / 2;
        double y = Border;

        Point point = new Point(
                x,
                y
                );

        // Move to position
        textgenerator.moveTo(point);
        // Add page number
        textgenerator.show(stampText);
    }
    finally
    {
        if (textgenerator != null)
            textgenerator.close();
    }

    // Paint the positioned text 
    generator.paintText(text);
}

Fit pages to specific page format

Fit each page of a PDF document to a specific page format.

l'exemple C# :
// Open input document
Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read);
Document inDoc = Document.Open(inStream, null);

// Create output document 
Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite);
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
{
    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Set copy options
    CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | 
        CopyOption.CopyFormFields | CopyOption.CopyOutlines | CopyOption.CopyLogicalStructure;

    // Copy pages
    foreach (Page inPage in inDoc.Pages)
    {
        Page outPage = null;
        Size pageSize = inPage.Size;

        bool rotate = AllowRotate && 
            (pageSize.Height >= pageSize.Width) != (TargetSize.Height >= TargetSize.Width);
        Size rotatedSize = pageSize;

        if (rotate)
            rotatedSize = new Size { Width = pageSize.Height, Height = pageSize.Width };

        if (rotatedSize.Width == TargetSize.Width && rotatedSize.Height == TargetSize.Width)
        {
            // If size is correct, copy page only
            outPage = outDoc.CopyPage(inPage, copyOptions);

            if (rotate)
                outPage.Rotate(Rotation.Clockwise);
        }
        else
        {
            // Create new page of correct size and fit existing page onto it
            outPage = outDoc.CreatePage(TargetSize);

            // Copy page as group
            using (Group group = outDoc.CopyPageAsGroup(inPage, copyOptions))
            {
                // Calculate scaling and position of group
                double scale = Math.Min(TargetSize.Width / rotatedSize.Width,
                    TargetSize.Height / rotatedSize.Height);

                // Calculate position
                Point position = new Point
                {
                    X = (TargetSize.Width - pageSize.Width * scale) / 2,
                    Y = (TargetSize.Height - pageSize.Height * scale) / 2
                };

                // Create content generator
                using (ContentGenerator generator = new ContentGenerator(outPage.Content, false))

                // Calculate and apply transformation
                using (Transformation transformation = new Transformation())
                {
                    transformation.Translate(position.X, position.Y);
                    transformation.Scale(scale, scale);

                    Point point = new Point()
                    {
                        X = pageSize.Width / 2.0,
                        Y = pageSize.Height / 2.0
                    };

                    // Rotate input file 
                    if (rotate)
                        transformation.RotateAround(90, point);
                    generator.Transform(transformation);

                    // Paint group
                    generator.PaintGroup(group, null, null);
                }
            }
        }
        // Add page to output document 
        outDoc.Pages.Add(outPage);
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

try
{
    // Create output document
    outStream = new FileStream(outPath, "rw");
    outStream.setLength(0);
    outDoc = Document.create(outStream, Conformance.UNKNOWN, null);

    // Set output intent 
    if (inDoc.getOutputIntent() != null) 
        outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

    // Copy metadata 
    Metadata metadata =  outDoc.copyMetadata(inDoc.getMetadata());
    outDoc.setMetadata(metadata);

    // Set copy options
    EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_LINKS, CopyOption.COPY_ANNOTATIONS,
          CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES, CopyOption.COPY_LOGIGAL_STRUCTURE);

    // Copy pages
    for (Page inPage : inDoc.getPages())
    {
        Page outPage = null;
        Size pageSize = inPage.getSize();

        boolean rotate = AllowRotate && (pageSize.height >= pageSize.width) != 
            (TargetSize.height >= TargetSize.width);
        Size rotatedSize = pageSize;

        if (rotate)
            rotatedSize = new Size(pageSize.height, pageSize.width);

        if (rotatedSize.width == TargetSize.width && rotatedSize.height == TargetSize.height)
        {
            // If size is correct, copy page only
            outPage = outDoc.copyPage(inPage, copyOptions);

            if (rotate)
                outPage.rotate(Rotation.CLOCKWISE);
        }
        else
        {
            // Create new page of correct size and fit existing page onto it
            outPage = outDoc.createPage(TargetSize);

            // Copy page as group 
            Group group = outDoc.copyPageAsGroup(inPage, copyOptions);

            // Calculate scaling and position of group 
            double scale = Math.min(TargetSize.width / rotatedSize.width, 
                TargetSize.height / rotatedSize.height);

            // Calculate position
            Point position = new Point(
                    (TargetSize.width - pageSize.width * scale) / 2, 
                    (TargetSize.height - pageSize.height * scale) / 2
                    );

            ContentGenerator generator = null;
            try
            {
                // Create content generator
                generator = new ContentGenerator(outPage.getContent(), false);

                // Calculate and apply transformation
                Transformation transformation = new Transformation();

                transformation.translate(position.x, position.y);
                transformation.scale(scale, scale);

                Point point = new Point(
                        pageSize.width / 2.0,
                        pageSize.height / 2.0
                        );

                // Rotate input file
                if (rotate)
                    transformation.rotateAround(90, point);
                generator.transform(transformation);

                // Paint group 
                generator.paintGroup(group, null, null);
            }
            finally
            {
                // Close content generator
                if (generator != null)
                    generator.close();
            }
        }
        // Add page
        outDoc.getPages().add(outPage);
        outPage.close();
        inPage.close();
    }
}
finally
{
    // Close output document
    if (outDoc != null)
        outDoc.close();
    if (outStream != null)
        outStream.close();
}

Place multiple pages on one page

Place four pages of a PDF document on a single page.

l'exemple C# :
// Create output document 
using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outStream, Conformance.Unknown, null))
using (PageList outPages = outDoc.Pages)
{
    int pageCount = 0;
    ContentGenerator generator = null;
    Page outPage = null;

    // Open input document
    using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
    using (Document inDoc = Document.Open(inStream, null))
    {
        // Set output intent
        using (ColorSpace inIntent = inDoc.OutputIntent)
        {
            if (inIntent != null)
                using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
                    outDoc.OutputIntent = outputIntent;
        }

        // Copy metadata
        using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
            outDoc.Metadata = metadata;

        // Copy pages 
        using (PageList inPages = inDoc.Pages)
        {
            // Copy pages
            foreach (Page inPage in inPages)
            {
                if (pageCount == Nx * Ny)
                {
                    // Add to output document
                    generator.Dispose();
                    outPages.Add(outPage);
                    outPage.Dispose();
                    outPage = null;
                    pageCount = 0;
                }
                if (outPage == null)
                {
                    // Create a new output page
                    outPage = outDoc.CreatePage(PageSize);
                    generator = new ContentGenerator(outPage.Content, false);
                }

                // Get area where group has to be
                int x = pageCount % Nx;
                int y = Ny - (pageCount / Nx) - 1;

                // Calculate cell size
                Size cellSize = new Size
                {
                    Width = (PageSize.Width - ((Nx + 1) * Border)) / Nx,
                    Height = (PageSize.Height - ((Ny + 1) * Border)) / Ny
                };

                // Calculate cell position
                Point cellPosition = new Point
                {
                    X = Border + x * (cellSize.Width + Border),
                    Y = Border + y * (cellSize.Height + Border)
                };

                // Set copy option
                CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | 
                    CopyOption.CopyFormFields | CopyOption.CopyOutlines |
                    CopyOption.CopyLogicalStructure;

                // Copy page group from input to output
                using (Group group = outDoc.CopyPageAsGroup(inPage, copyOptions))
                {
                    // Calculate group position 
                    Size groupSize = group.Size;
                    double scale = Math.Min(cellSize.Width / groupSize.Width, 
                        cellSize.Height / groupSize.Height);

                    // Calculate target size
                    Size targetSize = new Size
                    {
                        Width = groupSize.Width * scale,
                        Height = groupSize.Height * scale
                    };

                    // Calculate position
                    Point targetPos = new Point
                    {
                        X = cellPosition.X + ((cellSize.Width - targetSize.Width) / 2),
                        Y = cellPosition.Y + ((cellSize.Height - targetSize.Height) / 2)
                    };

                    // Calculate rectangle
                    Rectangle targetRect = new Rectangle
                    {
                        Left = targetPos.X,
                        Bottom = targetPos.Y,
                        Right = targetPos.X + targetSize.Width,
                        Top = targetPos.Y + targetSize.Height
                    };
                    // Add group to page
                    generator.PaintGroup(group, targetRect, null);
                }
                pageCount++;
            }
        }
    }
    // Add page
    if (outPage != null)
    {
        generator.Dispose();
        outPages.Add(outPage);
        outPage.Dispose();
    }
}
l'exemple Java :
    // Create output document
    outStream = new FileStream(outPath, "rw");
    outStream.setLength(0);
    outDoc = Document.create(outStream, Conformance.UNKNOWN, null);

    outPages = outDoc.getPages();

    int pageCount = 0;
    FileStream inStream = null;
    Document inDoc = null;
    ContentGenerator generator = null;
    Page outPage = null;

    try
    {
        // Open input document 
        inStream = new FileStream(inPath, "r");
        inDoc = Document.open(inStream, null);

        // Set output intent
        if (inDoc.getOutputIntent() != null)
            outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

        // Copy metadata
        Metadata metadata =  outDoc.copyMetadata(inDoc.getMetadata());
        outDoc.setMetadata(metadata);

        // Copy pages 
        for (Page inPage : inDoc.getPages()) 
        {

            if (pageCount == Nx * Ny)
            {
                // Add to output document
                generator.close();
                outPages.add(outPage);
                outPage.close();
                outPage = null;
                pageCount = 0;
            }
            if (outPage == null)
            {
                // Create a new output page
                outPage = outDoc.createPage(PageSize);
                generator = new ContentGenerator(outPage.getContent(), false);
            }

            // Get area where group has to be
            int x = pageCount % Nx;
            int y = Ny - (pageCount / Nx) - 1;

            // Calculate cell size
            Size cellSize = new Size(
                    (PageSize.width - ((Nx + 1) * Border)) / Nx, 
                    (PageSize.height - ((Ny + 1) * Border)) / Ny
                    );

            // Calculate cell position
            Point cellPosition = new Point(
                    Border + x * (cellSize.width + Border), 
                    Border + y * (cellSize.height + Border)
                    );

            // Set copy option
            EnumSet<CopyOption> copyoptions = EnumSet.of(CopyOption.COPY_LINKS, 
            CopyOption.COPY_ANNOTATIONS, CopyOption.COPY_FORM_FIELDS, CopyOption.COPY_OUTLINES,
            CopyOption.COPY_LOGIGAL_STRUCTURE);

            // Copy page group from input to output
            Group group = outDoc.copyPageAsGroup(inPage, copyoptions);

            // Calculate group position
            Size groupSize = group.getSize();
            double scale = Math.min(cellSize.width / groupSize.width,
                cellSize.height / groupSize.height);

            // Calculate target size 
            Size targetSize = new Size(
                    groupSize.width * scale, 
                    groupSize.height * scale
                    );

            // Calculate position 
            Point targetPos = new Point(
                    cellPosition.x + ((cellSize.width - targetSize.width) / 2), 
                    cellPosition.y + ((cellSize.height - targetSize.height) / 2)
                    );

            // Calculate rectangle 
            Rectangle targetRect = new Rectangle(
                    targetPos.x, 
                    targetPos.y, 
                    targetPos.x + targetSize.width, 
                    targetPos.y + targetSize.height
                    );

            // Add group to page
            generator.paintGroup(group, targetRect, null);

            inPage.close();
            pageCount++;
        }
    } 
    finally
    {
        // Close input document
        if (inDoc != null)
            inDoc.close();
        if (inStream != null)
            inStream.close();
    }

    // Add page
    if (outPage != null)
    {
        generator.close();
        outPages.add(outPage);
        outPage.close();
    }
}
catch (Exception e) 
{
    e.printStackTrace();
    System.exit(-1);
} 
finally 
{
    try 
    {
        // Close input document
        if (outDoc != null)
            outDoc.close();
        if (outStream != null)
            outStream.close();
    }
    catch (Exception e) 
    {
        e.printStackTrace();
        System.exit(-1);
    }
}

Set page orientation

Rotate a specified page of a PDF document by 90 degrees.

l'exemple C# :
// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))

// Create output document
using (Stream outFs = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
using (Document outDoc = Document.Create(outFs, Conformance.Unknown, null))
{
    // Set copy options
    CopyOption copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | 
        CopyOption.CopyFormFields | CopyOption.CopyOutlines | CopyOption.CopyLogicalStructure;

    // Set output intent
    if (inDoc.OutputIntent != null)
        using (ColorSpace outputIntent = outDoc.CopyColorSpace(inDoc.OutputIntent))
            outDoc.OutputIntent = outputIntent;

    // Copy metadata
    using (Metadata metadata = outDoc.CopyMetadata(inDoc.Metadata))
        outDoc.Metadata = metadata;

    // Loop through all pages of input
    for (int i = 1; i <= inDoc.Pages.Count; i++)
    {
        // Copy page from input to output
        using (Page inPage = inDoc.Pages[i - 1])
        using (Page outPage = outDoc.CopyPage(inPage, copyOptions))
        {
            if (pageNumbers.Contains(i))
            {
                // Rotate selected pages by 90°
                outPage.Rotate(Rotation.Clockwise);
            }
            // Add pages to document 
            outDoc.Pages.Add(outPage);
        }
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Create output document
outStream = new FileStream(outPath, "rw");
outStream.setLength(0);
outDoc = Document.create(outStream, Conformance.UNKNOWN, null);

// Set output intent
if (inDoc.getOutputIntent() != null)
    outDoc.setOutputIntent(outDoc.copyColorSpace(inDoc.getOutputIntent()));

// Copy metadata
outDoc.copyMetadata(inDoc.getMetadata());

// Set copy options and flatten annotations, form fields and signatures
EnumSet<CopyOption> copyOptions = EnumSet.of(CopyOption.COPY_OUTLINES, CopyOption.COPY_LINKS, CopyOption.FLATTEN_ANNOTATIONS, CopyOption.FLATTEN_FORM_FIELDS, CopyOption.FLATTEN_SIGNATURE_APPEARANCES, CopyOption.COPY_LOGIGAL_STRUCTURE);

// Loop through all pages of input
for (int i = 1; i <= inDoc.getPages().size(); i++)
{
    Page inPage = inDoc.getPages().get(i - 1);

    // Copy page from input to output
    Page outPage = outDoc.copyPage(inPage, copyOptions);

    for (int pages : pageNumbers)
    {
        if (pages == i)
        {
            // Rotate selected pages by 90°
            outPage.rotate(Rotation.CLOCKWISE);
        }
    } 
    // Add pages to document
    outDoc.getPages().add(outPage);

    // Cleanup
    if (outPage != null)
        outPage.close();
    if (inPage != null)
        inPage.close();
}

Information Extraction

List document information of PDF

List document information of a PDF document, e.g. author, title, creation date etc.

l'exemple C# :
// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))
{
    // Get metadata of input PDF
    Metadata metadata = inDoc.Metadata;
    Console.WriteLine("Document information:");

    // Get title
    string title = metadata.Title;
    if (title != null)
        Console.WriteLine("  - Title: {0}", title);

    // Get author
    string author = metadata.Author;
    if (author != null)
        Console.WriteLine("  - Author: {0}", author);

    // Get creator
    string creator = metadata.Creator;
    if (creator != null)
        Console.WriteLine("  - Creator: {0}", creator);

    // Get subject
    string subject = metadata.Subject;
    if (subject != null)
        Console.WriteLine("  - Subject: {0}", subject);

    // Get producer
    string producer = metadata.Producer;
    if (producer != null)
        Console.WriteLine("  - Producer: {0}", producer);

    // Get creation date
    DateTime? creationDate = (DateTime?)metadata.CreationDate;
    if (creationDate != null)
        Console.WriteLine("  - Creation Date: {0}", creationDate);

    // Get keywords
    string keywords = metadata.Keywords;
    if (keywords != null)
        Console.WriteLine("  - Keywords: {0}", keywords);

    // Get modification date
    DateTime? modificationDate = (DateTime?)metadata.ModificationDate;
    if (modificationDate != null)
        Console.WriteLine("  - Modification Date: {0}", modificationDate);
}
l'exemple Java :
// Open input document 
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

// Get metadata of input PDF
Metadata metadata = inDoc.getMetadata();
System.out.format("Document information:\n");

// Get title
String title = metadata.getTitle();
if (title != null)
    System.out.format("  - Title: %s\n", title);

// Get author
String author = metadata.getAuthor();
if (author != null)
    System.out.format("  - Author: %s\n", author);

// Get creator
String creator = metadata.getCreator();
if (creator != null)
    System.out.format("  - Creator: %s\n", creator);

// Get subject
String subject = metadata.getSubject();
if (subject != null)
    System.out.format("  - Subject: %s\n", subject);

// Get producer
String producer = metadata.getProducer();
if (producer != null)
    System.out.format("  - Producer: %s\n", producer);

// Get creation date
Calendar creationDate = metadata.getCreationDate();
if (creationDate != null) 
{
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ssZ");
    format.setTimeZone(creationDate.getTimeZone());
    System.out.format("  - Creation Date: %s\n", format.format(creationDate.getTime()));
}

// Get keywords
String keywords = metadata.getKeywords();
if (keywords != null)
    System.out.format("  - Keywords: %s\n", keywords);

// Get modification date       
Calendar modificationDate = metadata.getModificationDate();
if (modificationDate != null) 
{
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ssZ");
    format.setTimeZone(modificationDate.getTimeZone());
    System.out.format("  - Modification Date: %s\n", format.format(modificationDate.getTime()));
}

List Signatures in PDF

List all signature fields in a PDF document and their properties.

l'exemple C# :
// Open input document
using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
using (Document inDoc = Document.Open(inStream, null))
{
    SignatureFieldList signatureFields = inDoc.SignatureFields;
    Console.WriteLine("Number of signature fields: {0}", signatureFields.Count);
    foreach (SignatureField sig in signatureFields)
    {
        if (sig.IsSigned)
        {
            // List name
            string name = sig.Name;
            Console.WriteLine("- {0} fields, signed by: {1}",
                sig.IsVisible ? "Visible" : "Invisible", name != null ? name : "(Unknown name)");

            // List location
            string location = sig.Location;
            if (location != null)
                Console.WriteLine("  - Location: {0}", location);

            // List reason 
            string reason = sig.Reason;
            if (reason != null)
                Console.WriteLine("  - Reason: {0}", reason);

            // List contact info
            string contactInfo = sig.ContactInfo;
            if (contactInfo != null)
                Console.WriteLine("  - Contact info: {0}", contactInfo);

            // List date
            DateTime date = (DateTime)sig.Date;
            if (date != null)
                Console.WriteLine("  - Date: {0}", date);
        }
        else
            Console.WriteLine("- {0} field, not signed", sig.IsVisible ? "Visible" : "Invisible");
    }
}
l'exemple Java :
// Open input document
inStream = new FileStream(inPath, "r");
inDoc = Document.open(inStream, null);

SignatureFieldList signatureFields = inDoc.getSignatureFields();
System.out.format("Number of signature fields: %d\n", signatureFields.size());

for (SignatureField sig : signatureFields)
{
    if (sig.getIsSigned()) 
    {
        // List name
        String name = sig.getName();
        System.out.format("- %s field, signed by: %s\n", sig.getIsVisible() ? "Visible" : "Invisible", name != null ? name : "(Unknown name)");

        // List location
        String location = sig.getLocation();
        if (location != null)
            System.out.format("  - Location: %s\n", location);

        // List reason
        String reason = sig.getReason();
        if (reason != null)
            System.out.format("  - Reason: %s\n", reason);

        // List contact info
        String contactInfo = sig.getContactInfo();
        if (contactInfo != null)
            System.out.format("  - Contact info: %s\n", contactInfo);

        // List date
        Calendar date = sig.getDate();
        if (date != null)
        {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
            format.setTimeZone(date.getTimeZone());
            System.out.format("  - Date: %s\n", format.format(date.getTime()));
        }
    }
    else
    {
        System.out.format("- %s field, not signed\n", sig.getIsVisible() ? "Visible" : "Invisible");
    }
}