背景和前景
为了在 PDF 文档中添加特定的背景或前景元素,IronPDF 提供了 addBackground
和 addForeground
方法。通过这些方法,开发人员可以将一个 PDF 的内容用作另一个 PDF 的背景或前景。这些方法尤其适用于生成基于共同设计模板的 PDF 群组。
addBackground(PdfDocument backgroundPdf);
addForeground(PdfDocument foregroundPdf);
由于这些方法适用于 PdfDocument
对象,因此开发人员可以使用 fromFile
方法从现有文件中获取这些方法,或使用其中一种可用的 PDF 渲染方法重新生成这些方法。
addBackground
和 addForeground
默认使用多页 PDF 文档的第一页作为背景或前景。要在包含多页的 PDF 文件中使用不同的页面,请在方法调用的第二个参数中添加所需页的索引。
// Use the third page of the background PDF as the background of every page
// in the working PDF
pdf.addBackground(backgroundPdf, 2);
// Use the second page of the foreground PDF as the foreground of every page
// of the working PDF
pdf.addForeground(foregroundPdf, 1);
要在 PDF 文档的特定页面上将 PDF 叠加为背景或前景,可使用 PageSelection
对象指定要叠加的页面。下面的示例展示了如何为 PDF 文档的单页和一系列页面进行叠加。
// Add the background to page 5 of the working PDF
pdf.addBackground(backgroundPdf, PageSelection.singlePage(6));
// Add a different background on pages 7 through 16 of the working PDF
pdf.addBackground(backgroundPdf, PageSelection.pageRange(6, 15));
// Add another background to just the first page.
pdf.addBackground(backgroundPdf, PageSelection.firstPage());
在 PDF 文档中添加水印时,可使用 addWatermark
方法替代 addBackground
方法,以便更轻松地控制背景位置和不透明度。