How to hide layers when merging multiple pdf documents

496 Views Asked by At

I'm using iText 5 to fill existing pdf forms with content and then merge them into a single pdf. I also want to turn on/off layers, but after merging all layers are visible.

This code shows the problem without using existing pdf forms. I would like to hide layer two but it seems not working.

    static void Main(string[] args)
    {
        byte[] pdfPage = CreatePage();
        byte[] result = Merge(new byte[][] { pdfPage, pdfPage });
        File.WriteAllBytes(@"c:\test1.pdf", result);
    }

    private static byte[] CreatePage()
    {
        Document doc = new Document();
        MemoryStream ms = new MemoryStream();
        PdfWriter writer = PdfWriter.GetInstance(doc, ms);
        doc.Open();
        PdfLayer layer1 = new PdfLayer("Layer 1", writer);
        PdfLayer layer2 = new PdfLayer("Layer 2", writer);
        PdfContentByte cb = writer.DirectContent;
        cb.BeginLayer(layer1);
        ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("Layertext 1"), 100, 700, 0);
        cb.EndLayer();
        cb.BeginLayer(layer2);
        ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("Layertext 2"), 100, 600, 0);
        cb.EndLayer();
        layer1.On = true;
        // turn off layer 2
        layer2.On = false;
        doc.Close();
        return ms.ToArray();
    }

    private static byte[] Merge(byte[][] pages)
    {
        Document doc = new Document();
        MemoryStream ms = null;
        using (ms = new MemoryStream())
        {
            PdfCopy copy = new PdfCopy(doc, ms);
            doc.Open();
            foreach (byte[] page in pages)
            {
                PdfReader reader = new PdfReader(new MemoryStream(page));
                PdfImportedPage imp = copy.GetImportedPage(reader, 1);
                copy.AddPage(imp);
                reader.Close();
            }
            doc.Close();
        }
        return ms.ToArray();
    }
0

There are 0 best solutions below