Skip to content
Demo示例FAQ

PDF 生成模板编辑器

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

查看 GitHub
Android Guides Pdfa

PDF 标准转换 ​

ComPDF 使用 CPDFDocument.convertType() 将已打开的 PDF 转换为指定标准类型。转换会调整文档内容或资源,能否完成取决于源文件及目标类型,应检查返回结果并保存输出。

选择目标类型 ​

类型PDFDocumentType 枚举
PDF/A-1PDFTypeA1a、PDFTypeA1b
PDF/A-2PDFTypeA2a、PDFTypeA2u、PDFTypeA2b
PDF/A-3PDFTypeA3a、PDFTypeA3u、PDFTypeA3b
PDF/XPDFTypeX1a、PDFTypeX3、PDFTypeX4
PDF/EPDFTypeE1、PDFTypeE2
PDF/VTPDFTypeVT1、PDFTypeVT2
PDF/UAPDFTypeUA1

当前枚举不包含 PDF/A-4。不要将标准名称或枚举值之外的类型当作支持范围。

转换、保存与检查 ​

以下示例将已打开的 document 转换为 PDF/A-2b。outputPath 为可写的新文件路径,父目录已创建。操作应在后台线程执行。

java
CPDFDocument.PDFDocumentType target = CPDFDocument.PDFDocumentType.PDFTypeA2b;
if (document.convertType(target)) {
    try {
        boolean saved = document.saveAs(outputPath, false);
        if (saved) {
            CPDFDocument output = new CPDFDocument(context);
            try {
                if (output.open(outputPath)
                        == CPDFDocument.PDFDocumentError.PDFDocumentErrorSuccess) {
                    boolean matches = output.getType() == target;
                    // 根据 matches 检查保存后的文档类型。
                }
            } finally {
                output.close();
            }
        }
    } catch (CPDFDocumentException e) {
        // 转换已完成,但保存失败;按实际情况重试或提示。
    }
} else {
    // 转换失败,不按成功结果继续保存。
}
kotlin
val target = CPDFDocument.PDFDocumentType.PDFTypeA2b
if (document.convertType(target)) {
    try {
        if (document.saveAs(outputPath, false)) {
            val output = CPDFDocument(context)
            try {
                if (output.open(outputPath) ==
                    CPDFDocument.PDFDocumentError.PDFDocumentErrorSuccess) {
                    val matches = output.type == target
                    // 根据 matches 检查保存后的文档类型。
                }
            } finally {
                output.close()
            }
        }
    } catch (e: CPDFDocumentException) {
        // 处理保存失败。
    }
} else {
    // 处理转换失败。
}

示例使用 CPDFDocument 和 CPDFDocumentException,分别位于 com.compdfkit.core.document 和 com.compdfkit.core.common 包。

使用说明 ​

  • 加密文档应先通过 saveAs(path, true) 移除加密,重新打开解密后的文件再转换。
  • convertType() 修改当前文档的内存内容,成功后仍需保存。关闭不再使用的文档实例。
  • getType() 用于检查 SDK 识别的保存类型,不能代替独立的标准合规验证。对输出有合规要求时,应按交付要求另行验证。

查看其他格式转换能力,参见 Conversion SDK。