PDF Generation Template Editor
Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.
Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.
ComPDF PDF SDK for Flutter lets you create a new PDF document without first opening a local PDF file. Use this feature to generate reports, receipts, forms, or other PDF files dynamically in your app.
After creating a document, you can insert pages, add annotations or form fields, and save the document to a specified location.
Initialize the SDK before creating a document. For initialization instructions, see Apply the License Key.
Call CPDFDocument.createDocument() to create a document instance. A newly created document has no pages, so insert a page before saving it as a PDF file.
import 'dart:io';
import 'package:compdfkit_flutter/compdfkit.dart';
import 'package:compdfkit_flutter/configuration/cpdf_configuration.dart';
import 'package:compdfkit_flutter/document/cpdf_document.dart';
import 'package:compdfkit_flutter/page/cpdf_page.dart';
Future<String> createPdfDocument() async {
CPDFDocument? document;
try {
document = await CPDFDocument.createDocument();
final inserted = await document.insertBlankPage(
pageIndex: 0,
pageSize: CPDFPageSize.a4,
);
if (!inserted) {
throw StateError('Failed to insert a blank page.');
}
final directory = await ComPDFKit.getTemporaryDirectory();
final savePath =
'${directory.path}${Platform.pathSeparator}new_document.pdf';
final saved = await document.saveAs(savePath);
if (!saved) {
throw StateError('Failed to save the PDF document.');
}
return savePath;
} finally {
await document?.close();
}
}createPdfDocument() returns the path of the generated PDF file. After saving the document, open it in the Reader:
final documentPath = await createPdfDocument();
ComPDFKit.openDocument(
documentPath,
configuration: CPDFConfiguration(),
);The document instance returned by CPDFDocument.createDocument() supports the other CPDFDocument APIs. For example, you can:
insertBlankPage() or insertPageWithImagePath().addAnnotations().addWidgets().saveAs().The example saves the file in the app's temporary directory, which the operating system may clear. To retain the file, provide saveAs() with a path in persistent storage or a location selected by the user.