如何在将现有pdf与从头创建的pdf连接时保留页面标签?

如何在将现有pdf与从头创建的pdf连接时保留页面标签?,pdf,itext,Pdf,Itext,我有一个代码,创建一个“封面”,然后将其与现有的pdf合并。合并后pdf标签丢失。如何保留现有pdf的pdf标签,然后将页面标签添加到从头创建的pdf页面(例如“封面”)?我想这本书的例子是关于检索和替换页面标签的。我不知道在将现有pdf与从头创建的pdf连接起来时如何应用这一点。我正在使用itext 5.3.0。提前谢谢 编辑 根据mkl的意见 public ByteArrayOutputStream getConcatenatePDF() { if (bitstream == nul

我有一个代码,创建一个“封面”,然后将其与现有的pdf合并。合并后pdf标签丢失。如何保留现有pdf的pdf标签,然后将页面标签添加到从头创建的pdf页面(例如“封面”)?我想这本书的例子是关于检索和替换页面标签的。我不知道在将现有pdf与从头创建的pdf连接起来时如何应用这一点。我正在使用itext 5.3.0。提前谢谢

编辑 根据mkl的意见

public ByteArrayOutputStream getConcatenatePDF()
{
    if (bitstream == null)
        return null;

    if (item == null)
    {
        item = getItem();
        if (item == null)
            return null;
    }

    ByteArrayOutputStream byteout = null;
    InputStream coverStream = null;

    try
    {
        // Get Cover Page
        coverStream = getCoverStream();
        if (coverStream == null) 
            return null;

        byteout = new ByteArrayOutputStream();
        int pageOffset = 0;
        ArrayList<HashMap<String, Object>> master = new ArrayList<HashMap<String, Object>>();

        Document document = null;
        PdfCopy    writer = null;
        PdfReader  reader = null;

        byte[] password = (ownerpass != null && !"".equals(ownerpass)) ? ownerpass.getBytes() : null;

        // Get infomation of the original pdf
        reader = new PdfReader(bitstream.retrieve(), password);

        boolean isPortfolio = reader.getCatalog().contains(PdfName.COLLECTION);
        char version = reader.getPdfVersion();
        int permissions = reader.getPermissions();

        // Get metadata
        HashMap<String, String> info = reader.getInfo();
        String title = (info.get("Title") == null || "".equals(info.get("Title")))
            ? getFieldValue("dc.title") : info.get("Title");
        String author = (info.get("Author") == null || "".equals(info.get("Author")))
            ? getFieldValue("dc.contributor.author") : info.get("Author");
        String subject = (info.get("Subject") == null || "".equals(info.get("Subject")))
            ? "" : info.get("Subject");
        String keywords = (info.get("Keywords") == null || "".equals(info.get("Keywords")))
            ? getFieldValue("dc.subject") : info.get("Keywords");

        reader.close();

        // Merge cover page and the original pdf
        InputStream[] is = new InputStream[2];
        is[0] = coverStream;
        is[1] = bitstream.retrieve();

        for (int i = 0; i < is.length; i++) 
        {
            // we create a reader for a certain document
            reader = new PdfReader(is[i], password);
            reader.consolidateNamedDestinations();

            if (i == 0) 
            {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));

                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, byteout);

                // Set metadata from the original pdf 
                // the position of these lines is important
                document.addTitle(title);
                document.addAuthor(author);
                document.addSubject(subject);
                document.addKeywords(keywords);

                if (pdfa)
                {
                    // Set thenecessary information for PDF/A-1B
                    // the position of these lines is important
                    writer.setPdfVersion(PdfWriter.VERSION_1_4);
                    writer.setPDFXConformance(PdfWriter.PDFA1B);
                    writer.createXmpMetadata();
                }
                else if (version == '5')
                    writer.setPdfVersion(PdfWriter.VERSION_1_5);
                else if (version == '6')
                    writer.setPdfVersion(PdfWriter.VERSION_1_6);
                else if (version == '7')
                    writer.setPdfVersion(PdfWriter.VERSION_1_7);
                else
                    ;  // no operation

                // Set security parameters
                if (!pdfa)
                {
                    if (password != null)
                    {
                        if (security && permissions != 0) 
                        {
                            writer.setEncryption(null, password, permissions, PdfWriter.STANDARD_ENCRYPTION_128);
                        } 
                        else
                        {
                            writer.setEncryption(null, password, PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STANDARD_ENCRYPTION_128);
                        }
                    }
                }

                // step 3: we open the document
                document.open();

                // if this pdf is portfolio, does not add cover page
                if (isPortfolio)
                {
                    reader.close();
                    byte[] coverByte = getCoverByte();
                    if (coverByte == null || coverByte.length == 0) 
                        return null;
                    PdfCollection collection = new PdfCollection(PdfCollection.TILE);
                    writer.setCollection(collection);

                    PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(writer, null, "cover.pdf", coverByte);
                    fs.addDescription("cover.pdf", false);
                    writer.addFileAttachment(fs);
                    continue;
                }
            }
            int n = reader.getNumberOfPages();
            // step 4: we add content
            PdfImportedPage page;
            PdfCopy.PageStamp stamp;
            for (int j = 0; j < n; )
            {
                ++j;
                page = writer.getImportedPage(reader, j);
                if (i == 1) {
                    stamp = writer.createPageStamp(page);
                    Rectangle mediabox = reader.getPageSize(j);
                    Rectangle crop = new Rectangle(mediabox);
                    writer.setCropBoxSize(crop);
                    // add overlay text
                    //<-- Code for adding overlay text -->
                    stamp.alterContents();
                }
                writer.addPage(page);
            }

            PRAcroForm form = reader.getAcroForm();
            if (form != null && !pdfa)
            {
                writer.copyAcroForm(reader);
            }
            // we retrieve the total number of pages
            List<HashMap<String, Object>> bookmarks = SimpleBookmark.getBookmark(reader);
            //if (bookmarks != null && !pdfa) 
            if (bookmarks != null) 
            {
                if (pageOffset != 0)
                {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += n;
        }
        if (!master.isEmpty())
        {
            writer.setOutlines(master);
        }

        if (isPortfolio)
        {
            reader = new PdfReader(bitstream.retrieve(), password);
            PdfDictionary catalog = reader.getCatalog();
            PdfDictionary documentnames = catalog.getAsDict(PdfName.NAMES);
            PdfDictionary embeddedfiles = documentnames.getAsDict(PdfName.EMBEDDEDFILES);
            PdfArray filespecs = embeddedfiles.getAsArray(PdfName.NAMES);
            PdfDictionary filespec;
            PdfDictionary refs;
            PRStream stream;
            PdfFileSpecification fs;
            String path;
            // copy embedded files
            for (int i = 0; i < filespecs.size(); ) 
            {
                filespecs.getAsString(i++);     // remove description
                filespec = filespecs.getAsDict(i++);
                refs = filespec.getAsDict(PdfName.EF);
                for (PdfName key : refs.getKeys()) 
                {
                    stream = (PRStream) PdfReader.getPdfObject(refs.getAsIndirectObject(key));
                    path = filespec.getAsString(key).toString();
                    fs = PdfFileSpecification.fileEmbedded(writer, null, path, PdfReader.getStreamBytes(stream));
                    fs.addDescription(path, false);
                    writer.addFileAttachment(fs);
                }
            }
        }

        if (pdfa)
        {
            InputStream iccFile = this.getClass().getClassLoader().getResourceAsStream(PROFILE);
            ICC_Profile icc = ICC_Profile.getInstance(iccFile);
            writer.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        }
        // step 5: we close the document
        document.close();
    } 
    catch (Exception e) 
    {
        log.info(LogManager.getHeader(context, "cover_page: getConcatenatePDF", "bitstream_id="+bitstream.getID()+", error="+e.getMessage()));
        // e.printStackTrace();
        return null;
    }

    return byteout;
}
修改后的代码保留了现有pdf的页面标签(请参见屏幕截图1)(
documentStream
),但生成的合并pdf(屏幕截图2和3)自插入封面后关闭了1页。正如mkl所建议的,我应该在封面上使用页面标签,但似乎导入页面的pdf标签丢失了。我现在关心的是如何将页面标签设置为最终文档状态,正如mkl所建议的那样?我想我应该使用PdfWriter,但我不知道在修改后的代码中应该放在哪里。假设
stamper.close()部分之后是文档的最终状态,对吗?提前再次感谢

屏幕截图1。请注意标有封面的实际页面1

屏幕截图2.插入即时生成的“封面”后,合并了pdf。页面标签“封面”现在已分配给封面,即使我已使用
labels设置插入页面的pdf标签。addPageLabel(1,PdfPageLabels.EMPTY,“封面”,1)

屏幕截图3。请注意,页面标签3已分配给页面2。

最终更新 荣誉 下面的屏幕截图是我应用mkl答案的最新更新后的结果。页面标签现在已正确分配给页面。另外,使用PdfStamper而不是PdfCopy(在我的原始代码中使用)并没有破坏现有PDF的PDF/A遵从性

添加封面 通常使用
PdfCopy
合并PDF是正确的选择,它从复制的页面创建一个新文档,复制尽可能多的页面级信息,而不喜欢任何单个文档

不过,您的案例有些特殊:您有一个文档,您喜欢它的结构和内容,并且希望通过添加一个页面,一个标题页,对它进行一些小的更改。同时,主文件中的所有信息,包括文件级信息(如元数据、嵌入文件等),仍应存在于结果中

在这种情况下,更适合使用
PdfStamper
,您可以使用它将更改“标记”到现有PDF上

您可能希望从以下内容开始:

PS:关于评论中的问题:

在上面的代码中,我应该有一个覆盖文本(在stamp.alterContents()部分之前),但出于测试目的,我省略了代码的这一部分。你能告诉我如何实施吗

你的意思是像水印一样的东西吗?
PdfStamper
允许您访问每个页面的“过度内容”,您可以在其中绘制任何内容:

PdfContentByte overContent = stamper.getOverContent(pageNumber);
保留页面标签 我的另一个问题是关于页面偏移量,因为我插入了封面,页面编号减少了1页。我如何解决这个问题

不幸的是,iText的
PdfStamper
不会自动更新被操纵PDF的页面标签定义。实际上这并不奇怪,因为不清楚插入的页面是如何标记的@不过,至少Bruno,iText可以更改插入页码之后开始的页面标签部分

不过,使用iText的低级API可以修复原始标签位置并为插入的页面添加标签。这可以类似于iText的动作示例来实现,更确切地说是它的
manufactualAppageLabel
部分;只需在母版.close()之前添加:

您可以在插入原始页面后立即调用:

        PdfImportedPage page = stamper.getImportedPage(titleReader, 1);
        stamper.insertPage(1, titleReader.getPageSize(1));
        PdfContentByte content = stamper.getUnderContent(1);
        content.addTemplate(page, 0, 0);
        copyLinks(stamper, 1, titleReader, 1);

注意,此方法非常简单。它只考虑具有URI操作的链接,并使用与原始页面相同的位置、目标和突出显示设置在目标页面上创建链接。如果原始版本使用了更精细的功能(例如,如果它带来了自己的外观流,甚至仅仅使用了边框样式属性),并且您希望保留这些功能,那么您必须改进方法,将这些功能的条目复制到新注释中。

我有一个代码是。。。将其与现有pdf合并。-由于您没有显示该代码(许多人有不适当甚至不正确的合并例程),因此很难解释如何改进它。@mkl,我已经发布了部分代码。谢谢你的评论。我希望得到一个关于如何实现我想要的东西的例子,但是如果你能以某种方式改进我的代码,我将不胜感激。嗯,我看到你投入了大量的工作,将一个文档中的所有信息保存在合并副本中。我建议您对该文档使用PdfStamper,并将标题页作为第一页导入其中。这将自动保留所有原始文档级别的信息。我手边只有一部智能手机,因此无法详细说明。修改后的代码保留了现有pdf(documentStream)的页面标签,但结果合并后的pdf自插入封面后减少了1页。-你到底是什么意思?以前称为“1”的页面是否显示“2”,但您希望它仍然显示“1”?或者以前称为“1”的页面是否仍显示“1”,但您希望它显示“2”,因为之前已插入页面?是的,只有通过s PdfCopy导入的页面会自动保留交互功能。你
try (   InputStream documentStream = getClass().getResourceAsStream("template.pdf");
        InputStream titleStream = getClass().getResourceAsStream("title.pdf");
        OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "test-with-title-page.pdf"))    )
{
    PdfReader titleReader = new PdfReader(titleStream);
    PdfReader reader = new PdfReader(documentStream);
    PdfStamper stamper = new PdfStamper(reader, outputStream);

    PdfImportedPage page = stamper.getImportedPage(titleReader, 1);
    stamper.insertPage(1, titleReader.getPageSize(1));
    PdfContentByte content = stamper.getUnderContent(1);
    content.addTemplate(page, 0, 0);

    stamper.close();
}
PdfContentByte overContent = stamper.getOverContent(pageNumber);
    PdfDictionary root = reader.getCatalog();
    PdfDictionary labels = root.getAsDict(PdfName.PAGELABELS);
    if (labels != null)
    {
        PdfArray newNums = new PdfArray();

        newNums.add(new PdfNumber(0));
        PdfDictionary coverDict = new PdfDictionary();
        coverDict.put(PdfName.P, new PdfString("Cover Page"));
        newNums.add(coverDict);

        PdfArray nums = labels.getAsArray(PdfName.NUMS);
        if (nums != null)
        {
            for (int i = 0; i < nums.size() - 1; )
            {
                int n = nums.getAsNumber(i++).intValue();
                newNums.add(new PdfNumber(n+1));
                newNums.add(nums.getPdfObject(i++));
            }
        }

        labels.put(PdfName.NUMS, newNums);
        stamper.markUsed(labels);
    }
/**
 * <p>
 * A primitive attempt at copying links from page <code>sourcePage</code>
 * of <code>PdfReader reader</code> to page <code>targetPage</code> of
 * <code>PdfStamper stamper</code>.
 * </p>
 * <p>
 * This method is meant only for the use case at hand, i.e. copying a link
 * to an external URI without expecting any advanced features.
 * </p>
 */
void copyLinks(PdfStamper stamper, int targetPage, PdfReader reader, int sourcePage)
{
    PdfDictionary sourcePageDict = reader.getPageNRelease(sourcePage);
    PdfArray annotations = sourcePageDict.getAsArray(PdfName.ANNOTS);
    if (annotations != null && annotations.size() > 0)
    {
        for (PdfObject annotationObject : annotations)
        {
            annotationObject = PdfReader.getPdfObject(annotationObject);
            if (!annotationObject.isDictionary())
                continue;
            PdfDictionary annotation = (PdfDictionary) annotationObject;
            if (!PdfName.LINK.equals(annotation.getAsName(PdfName.SUBTYPE)))
                continue;

            PdfArray rectArray = annotation.getAsArray(PdfName.RECT);
            if (rectArray == null || rectArray.size() < 4)
                continue;
            Rectangle rectangle = PdfReader.getNormalizedRectangle(rectArray);

            PdfName hightLight = annotation.getAsName(PdfName.H);
            if (hightLight == null)
                hightLight = PdfAnnotation.HIGHLIGHT_INVERT;

            PdfDictionary actionDict = annotation.getAsDict(PdfName.A);
            if (actionDict == null || !PdfName.URI.equals(actionDict.getAsName(PdfName.S)))
                continue;
            PdfString urlPdfString = actionDict.getAsString(PdfName.URI);
            if (urlPdfString == null)
                continue;
            PdfAction action = new PdfAction(urlPdfString.toString());

            PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(), rectangle, hightLight, action);
            stamper.addAnnotation(link, targetPage);
        }
    }
}
        PdfImportedPage page = stamper.getImportedPage(titleReader, 1);
        stamper.insertPage(1, titleReader.getPageSize(1));
        PdfContentByte content = stamper.getUnderContent(1);
        content.addTemplate(page, 0, 0);
        copyLinks(stamper, 1, titleReader, 1);