合并多个pdf文档时如何隐藏图层

时间:2016-07-15 09:09:21

标签: pdf merge itext layer ocg

我使用iText 5用内容填充现有的pdf表单,然后将它们合并为单个pdf。我也想打开/关闭图层,但合并后所有图层都可见。

此代码在不使用现有pdf表单的情况下显示问题。我想隐藏第二层,但似乎无法正常工作。

    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 个答案:

没有答案