Skip to content
ComPDF

Best Practices

Resource Management

csharp
// Correct: Use using statement to ensure resource disposal
using (CDocument document = new CDocument())
using (CBorder border = new CBorder(1f))
using (CBorderRadius radius = new CBorderRadius(5f))
{
    // Use these resources
    document.SaveToFile("output.pdf");
}

// Not recommended: Manually call Dispose
CDocument document = new CDocument();
try
{
    document.SaveToFile("output.pdf");
}
finally
{
    document.Dispose();
}

Style Reuse

csharp
// Create reusable styles
CStyle bodyTextStyle = document.CreateStyle();
bodyTextStyle.SetFontSize(12);
bodyTextStyle.SetFontFamily("Arial");
bodyTextStyle.SetMarginBottom(10);

CStyle headingStyle = document.CreateStyle();
headingStyle.SetFontSize(18);
headingStyle.SetFontWeight(CFontWeight.Bold);
headingStyle.SetMarginTop(15);
headingStyle.SetMarginBottom(10);

// Apply to multiple elements
paragraph1.AddStyle(bodyTextStyle);
paragraph2.AddStyle(bodyTextStyle);
heading1.AddStyle(headingStyle);
heading2.AddStyle(headingStyle);

Performance Optimization

csharp
// 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.CreateText($"Item {i}");
    text.AddStyle(itemStyle); // Reuse style instead of setting each time
}

// 2. Use stream output instead of writing to memory first
using (FileStream fs = File.Create("large.pdf"))
{
    document.SaveToStream(fs);
}

Error Handling

csharp
try
{
    using (CDocument document = new CDocument())
    {
        CPage page = document.CreatePage(595, 842);
        
        // Validate image path
        string imagePath = "path/to/image.png";
        if (File.Exists(imagePath))
        {
            CImage image = page.CreateDiv().CreateImage(imagePath);
        }
        else
        {
            Console.WriteLine($"Image file does not exist: {imagePath}");
        }
        
        document.SaveToFile("output.pdf");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error generating PDF: {ex.Message}");
}