Search code examples
c#itext7

iText7 method return PdfFormXObject


I am working on reading a method that will return a PdfFormXObject but I dont understand CopyAsFormXObject. Its in the PdfPage method but the CopyAsFormXObject takes in a PdfDocument. Can it just be used from the PdfPage?

public static PdfFormXObject ReadAdobeIllustrator()
    {
        string mapPath = @"PathToAIFile.ai";
        byte[] b = null;
        var buffer = File.ReadAllBytes(mapPath);
        MemoryStream stream = new MemoryStream(buffer);
        PdfFormXObject pdfForm = null;
        using (MemoryStream returnMemoryStream = new MemoryStream())
        {
            iText.Kernel.Pdf.PdfReader PdfReader = new iText.Kernel.Pdf.PdfReader(stream);
            PdfDocument pdfDocument = new PdfDocument(PdfReader, new PdfWriter(returnMemoryStream));
            PdfPage origPage = pdfDocument.GetFirstPage();
            pdfForm = origPage.CopyAsFormXObject(pdfDocument);
            pdfDocument.Close();
            b = returnMemoryStream.ToArray();
        }

        return pdfForm;
    }

Solution

  • Please look at the method documentation:

    /// <summary>Copies page as FormXObject to the specified document.</summary>
    /// <param name="toDocument">a document to copy to.</param>
    /// <returns>
    /// copied
    /// <see cref="iText.Kernel.Pdf.Xobject.PdfFormXObject"/>
    /// object.
    /// </returns>
    public virtual PdfFormXObject CopyAsFormXObject(PdfDocument toDocument)
    

    Also there is no other overload of that method.

    Thus, you need to have the document in which the form XObject shall eventually be used when calling this method.

    In your code you use the source document as target. This obviously is wrong and cannot work.

    You may want to try something like this:

    public static PdfFormXObject ReadAdobeIllustrator(PdfDocument targetDocument)
    {
        using (PdfReader PdfReader = new PdfReader(@"PathToAIFile.ai"))
        using (PdfDocument pdfDocument = new PdfDocument(PdfReader))
        {
            PdfPage origPage = pdfDocument.GetFirstPage();
            return origPage.CopyAsFormXObject(targetDocument);
        }
    }
    

    (I'm not sure right now whether it is ok to close the source document - as I did here implicitly with using - before using the form XObject; I hardly ever need to assemble documents.)