Save PDF Documents
- 2 minutes to read
Use the PdfDocument.save() method to write a PDF document to an output stream or a writable channel. You can also specify SaveOptions for the save operation.
Save a Document to a Writable Channel
Use the save(WritableByteChannel channel, SaveOptions options) method to save a PDF document to a writable channel and specify save options.
The following code snippet loads a PDF document, adds a page, and saves the document using a writable channel:
import com.devexpress.docs.pdf.*;
import com.devexpress.drawing.printing.*;
import java.nio.channels.*;
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
try (FileChannel channel = FileChannel.open(Path.of("Document.pdf"));
PdfDocument pdfDocument = new PdfDocument(channel)) {
// Add an A4-size page to the document.
pdfDocument.getPages().add(DXPaperKind.A4);
// Configure save options.
SaveOptions saveOptions = new SaveOptions();
saveOptions.setUpdateCreatedAt(true);
saveOptions.setSyncMetadata(true);
// Save the document to a PDF file.
try (WritableByteChannel writableByteChannel =
FileChannel.open(Path.of("Document.pdf"),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING)) {
pdfDocument.save(writableByteChannel, saveOptions);
}
}
}
}
Save a Document to an Output Stream
Use the save(OutputStream stream) method to save a PDF document to an output stream.
The following code snippet loads a PDF document, adds a page, and saves the document using an output stream:
package barcodes;
import com.devexpress.docs.pdf.*;
import com.devexpress.drawing.printing.*;
import java.io.OutputStream;
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
try (InputStream stream =
Files.newInputStream(Path.of("Document.pdf"));
PdfDocument pdfDocument = new PdfDocument(stream)) {
// Add an A4-size page to the document.
pdfDocument.getPages().add(DXPaperKind.A4);
// Configure save options.
SaveOptions saveOptions = new SaveOptions();
saveOptions.setUpdateCreatedAt(true);
saveOptions.setSyncMetadata(true);
// Save the document to a PDF file.
try (OutputStream outputStream =
Files.newOutputStream(Path.of("Document.pdf"))) {
pdfDocument.save(outputStream);
}
}
}
}
See Also