Best Practices
Resource Management
java
CDocument document = new CDocument();
CBorder border = new CBorder(1f);
CBorderRadius radius = new CBorderRadius(5f)
// Use these resources
document.saveToFile("output.pdf");Style Reuse
java
// Create reusable styles
CStyle bodyTextStyle = document.createStyle();
bodyTextStyle
.setFontSize(12)
.setFontFamily("Arial");
bodyTextStyle.setMarginBottom(10);
CStyle headingStyle = document.createStyle();
headingStyle
.setFontSize(18)
.setFontWeight(CFontWeight.Bold);
headingStyle.setMarginTop(15)
.setMarginBottom(10);
// Apply to multiple elements
paragraph1.addStyle(bodyTextStyle);
paragraph2.addStyle(bodyTextStyle);
heading1.addStyle(headingStyle);
heading2.addStyle(headingStyle);Performance Optimization
java
// 1. When creating elements in bulk, consider pre-creating styles
CStyle itemStyle = document.createStyle();
itemStyle.setFontSize(12);
itemStyle.setMarginBottom(5);
for (int i = 0; i < 1000; i++) {
CText text = div.createTextElement("Item " + i);
text.addStyle(itemStyle); // Reuse style instead of setting each time
}
// 2. Use stream output instead of writing to memory first
try (FileOutputStream fos = new FileOutputStream("large.pdf")) {
document.saveToFile(fos);
} catch (IOException e) {
e.printStackTrace();
}Error Handling
java
try {
CDocument document = new CDocument();
CPage page = document.createPage(595, 842);
// Validate the image path
String imagePath = "path/to/image.png";
File imageFile = new File(imagePath);
if (imageFile.exists()) {
CImage image = page.createDivElement().createImageElement(imagePath);
} else {
System.out.println("Image file does not exist: " + imagePath);
}
document.saveToFile("output.pdf");
} catch (Exception ex) {
System.out.println("Error generating PDF: " + ex.getMessage());
ex.printStackTrace();
}