Skip to content

PDF 生成模板编辑器

开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。

查看 GitHub

背景

背景指文档页面的底层图层或底纹,用于呈现文档的基础视觉效果。添加背景可以改变文档的外观,使其更具个性化或专业性,可以用于强调品牌,保护版权,或提高文档的阅读体验。

在 PDF 文档中只能存在一个背景,对包含背景的文档页面添加背景会覆盖旧的背景。

设置颜色背景

设置颜色背景的步骤如下:

  1. 获取文档背景对象。

  2. 设置背景类型为颜色。

  3. 设置背景的属性。

  4. 将背景更新到文档上。

以下是设置颜色背景的示例代码:

java
CPDFDocument document = new CPDFDocument();
document.open("test.pdf");

CPDFBackground background = document.getBackground();
background.setType(CPDFBackground.Type.Color);
background.setColor(ColorUtils.parseColor(1f, 1f, 0f, 0f)); // RGBA
background.setOpacity(0.5f);
background.setRotation(45f);
background.setScale(1.0f);
background.setHorizalign(CPDFBackground.CPDFBackgroundAlign.Center);
background.setVertalign(CPDFBackground.CPDFBackgroundAlign.Center);
background.setXOffset(0f);
background.setYOffset(0f);
background.setPages("0,1,2");
background.setAllowsView(true);
background.setAllowsPrint(true);
background.update();

document.save(outputPath, CPDFDocument.PDFDocumentSaveType.PDFDocumentSaveNoIncremental);
background.release();
document.close();

设置图片背景

设置图片背景的步骤如下:

  1. 获取文档背景对象。

  2. 设置背景类型为图片。

  3. 设置背景属性。

  4. 将背景更新到文档上。

以下是设置图片背景的代码:

java
CPDFDocument document = new CPDFDocument();
document.open("test.pdf");

CPDFBackground background = document.getBackground();
background.setType(CPDFBackground.Type.Image);
background.setImage("ComPDFKit.png", "", null);
background.setOpacity(1.0f);
background.setScale(1.0f);
background.setHorizalign(CPDFBackground.CPDFBackgroundAlign.Center);
background.setVertalign(CPDFBackground.CPDFBackgroundAlign.Center);
background.setPages("0,1,2,3,4");
background.setAllowsView(true);
background.setAllowsPrint(true);
background.update();

document.save(outputPath, CPDFDocument.PDFDocumentSaveType.PDFDocumentSaveNoIncremental);
background.release();
document.close();

移除背景

移除背景的步骤如下:

  1. 获取文档背景对象。

  2. 删除文档背景。

以下是移除背景的代码:

java
CPDFDocument document = new CPDFDocument();
document.open(inputPath);
CPDFBackground background = document.getBackground();

System.out.println("isValid: " + background.isValid());
System.out.println("Type: " + background.getType());
System.out.println("Scale: " + background.getScale());
System.out.println("Rotation: " + background.getRotation());
System.out.println("Horizalign: " + background.getHorizalign());
System.out.println("Vertalign: " + background.getVertalign());
System.out.println("Pages: " + background.getPages());

background.clear();
document.save(outputPath, CPDFDocument.PDFDocumentSaveType.PDFDocumentSaveNoIncremental);
background.release();
document.close();