Cspdf is a powerful, feature-rich PDF library for .NET that provides comprehensive PDF creation, manipulation, and processing capabilities. It aims to be a complete alternative to commercial PDF libraries like iText 7.
- PDF Creation: Create PDF documents from scratch
- PDF Reading: Open and parse existing PDF documents
- PDF Manipulation: Merge, split, rotate, and modify PDFs
- Text Rendering: Draw text with custom fonts, colors, and styles
- Image Support: Add images to PDF documents
- Graphics Drawing: Draw shapes, lines, polygons, and paths
- Tables: Create and render tables with customizable styling
- Forms: Create interactive PDF forms (text fields, checkboxes, radio buttons, comboboxes)
- Watermarks: Add text or image watermarks to pages
- Digital Signatures: Sign PDF documents with certificates
- Security: Password protection and permission settings
- Bookmarks: Create document outlines and navigation
- Annotations: Add text annotations, highlights, links, and free text
- HTML to PDF: Convert HTML content to PDF
- Barcode Generation: Generate various barcode types (Code128, Code39, QR Code, etc.)
- Metadata: Set document metadata (title, author, subject, keywords, etc.)
- Text Extraction: Extract text content from PDF documents
- OCR Support: Interface for OCR (Optical Character Recognition) integration
- PDF/A Compliance: Create and validate PDF/A compliant documents
- Tagged PDF (PDF/UA): Create accessible PDFs with structure tags
- Stamping: Overlay content on existing PDF documents
- XFA Forms: Support for XFA (XML Forms Architecture) forms
- Redaction: Remove sensitive information from PDFs
- PDF Optimization: Optimize PDF file size and performance
- Page Numbering: Add page numbers with customizable formatting
- Data Extraction: Extract structured data from PDFs (pdf2Data equivalent)
dotnet add package CspdfOr via NuGet Package Manager:
Install-Package Cspdf
usingCspdf;usingSystem.Drawing;// Create a new PDF documentusingvardocument=newPdfDocument();// Add a pagevarpage=document.AddPage(PageSize.A4,PageOrientation.Portrait);vargraphics=page.Graphics;// Draw textusingvarfont=newFont("Arial",16,FontStyle.Bold);usingvarbrush=newSolidBrush(Color.Black);graphics.DrawString("Hello, Cspdf!",font,brush,50,50);// Save the documentdocument.Save("output.pdf");usingvardocument=newPdfDocument();varpage=document.AddPage();// Create a tablevartable=newPdfTable();table.ColumnWidths=newfloat[]{100,200,150};// Add headervarheaderRow=table.AddHeaderRow();headerRow.AddCell("Name");headerRow.AddCell("Email");headerRow.AddCell("Phone");// Add data rowstable.AddRow("John Doe","john@example.com","123-456-7890");table.AddRow("Jane Smith","jane@example.com","098-765-4321");// Draw the tabletable.Draw(page.Graphics,50,50,450);document.Save("table.pdf");usingvardocument=newPdfDocument();varpage=document.AddPage();// Create watermarkvarwatermark=newWatermark{Text="CONFIDENTIAL",Font=newFont("Arial",48,FontStyle.Bold),Color=Color.FromArgb(128,128,128,128),Rotation=-45f,Opacity=0.3f};// Apply to all pagesdocument.ApplyWatermark(watermark);document.Save("watermarked.pdf");varhtml=@"<html><body> <h1>Hello from HTML!</h1> <p>This is converted from HTML to PDF.</p></body></html>";vardocument=HtmlToPdf.Convert(html);document.Save("html-output.pdf");vardoc1=PdfDocument.Open("file1.pdf");vardoc2=PdfDocument.Open("file2.pdf");vardoc3=PdfDocument.Open("file3.pdf");varmerged=PdfDocument.Merge(doc1,doc2,doc3);merged.Save("merged.pdf");usingvardocument=newPdfDocument();varpage=document.AddPage();// Create text fieldvartextField=newPdfTextField{Name="name",Bounds=newRectangleF(50,50,200,30),Value="Enter your name"};// Create checkboxvarcheckbox=newPdfCheckBox{Name="agree",Bounds=newRectangleF(50,100,20,20),Checked=true};// Add to documentdocument.AddFormField(textField);document.AddFormField(checkbox);// Draw form fieldsforeach(varfieldindocument.FormFields){field.Draw(page.Graphics);}document.Save("form.pdf");usingvardocument=newPdfDocument();varpage=document.AddPage();// Generate barcodevarbarcode=BarcodeGenerator.GenerateBarcode("1234567890",BarcodeGenerator.BarcodeType.Code128,width:200,height:100);// Draw barcodepage.Graphics.DrawImage(barcode,50,50);document.Save("barcode.pdf");usingvardocument=newPdfDocument();// ... add content ...varsignature=newDigitalSignature{Certificate=newX509Certificate2("certificate.pfx","password"),Reason="Document approval",Location="Office",ContactInfo="contact@example.com"};usingvaroutputStream=newFileStream("signed.pdf",FileMode.Create);signature.Sign(document,outputStream);usingvardocument=PdfDocument.Open("document.pdf");// Extract all textvartext=document.ExtractText();Console.WriteLine(text);// Extract with positionsvarchunks=TextExtractor.ExtractTextWithPositions(document);foreach(varchunkinchunks){Console.WriteLine($"Page {chunk.PageIndex}: {chunk.Text} at ({chunk.X}, {chunk.Y})");}usingvardocument=newPdfDocument();// ... add content ...// Convert to PDF/A-2bvarpdfA=PdfACompliance.ConvertToPdfA(document,PdfAConformanceLevel.A2b);pdfA.Save("pdfa-document.pdf");// Validate PDF/A compliancevarresult=PdfACompliance.Validate(document,PdfAConformanceLevel.A2b);if(result.IsCompliant){Console.WriteLine("Document is PDF/A compliant!");}else{Console.WriteLine($"Errors: {string.Join(", ",result.Errors)}");}usingvardocument=PdfDocument.Open("existing.pdf");varstamper=document.CreateStamper();// Stamp text on first pagestamper.StampText(0,"APPROVED",50,50,newFont("Arial",24,FontStyle.Bold),newSolidBrush(Color.Green));// Stamp image on all pagesvarlogo=Image.FromFile("logo.png");for(inti=0;i<document.Pages.Count;i++){stamper.StampImage(i,logo,500,50);}document.Save("stamped.pdf");usingvardocument=PdfDocument.Open("document.pdf");varredactor=document.CreateRedactor();// Redact a region on page 0redactor.AddRedaction(0,newRectangleF(100,200,300,50),Color.Black);// Apply redactionsvarredacted=redactor.Apply();redacted.Save("redacted.pdf");usingvardocument=PdfDocument.Open("large.pdf");varoptions=newPdfOptimizer.OptimizationOptions{CompressImages=true,ImageQuality=85,RemoveUnusedObjects=true,Linearize=true};varoptimized=PdfOptimizer.Optimize(document,options);optimized.Save("optimized.pdf");// Get statisticsvarstats=PdfOptimizer.GetStatistics(document);Console.WriteLine($"Pages: {stats.PageCount}, Has Forms: {stats.HasForms}");usingvardocument=newPdfDocument();// ... add pages ...varoptions=newPageNumberOptions{Position=PageNumberPosition.BottomCenter,Format="Page {page} of {total}",Font=newFont("Arial",10),Color=Color.Gray};document.AddPageNumbers(options);document.Save("numbered.pdf");usingvardocument=PdfDocument.Open("invoice.pdf");vartemplate=newExtractionTemplate();template.AddField("InvoiceNumber",FieldType.Text).Label="Invoice #:";template.AddField("Amount",FieldType.Currency).Pattern=@"\$[\d,]+\.\d{2}";template.AddField("Date",FieldType.Date).Label="Date:";vardata=DataExtractor.ExtractData(document,template);varjson=DataExtractor.ExtractDataAsJson(document,template);Console.WriteLine(json);vardocument=newPdfDocument();// ... add pages ...varbookmark1=document.AddBookmark("Introduction",0);varbookmark2=document.AddBookmark("Chapter 1",1);bookmark1.AddChild("Section 1.1",2);varpage=document.AddPage();varannotation=newTextAnnotation{Bounds=newRectangleF(100,100,200,50),Title="Note",Contents="This is an important note",Icon="Note"};page.Annotations.Add(annotation);document.Security=newDocumentSecurity{UserPassword="user123",OwnerPassword="owner123",AllowPrinting=true,AllowCopy=false,AllowModifyContents=false};PdfDocument: Main document classPdfPage: Represents a page in the documentIGraphics: Interface for drawing operationsPdfTable: Table creation and renderingWatermark: Watermark functionalityDigitalSignature: Digital signature supportHtmlToPdf: HTML to PDF conversionBarcodeGenerator: Barcode generation
PageSize: A0, A1, A2, A3, A4, A5, A6, Letter, Legal, etc.PageOrientation: Portrait, Landscape
- .NET 8.0 or later
- System.Drawing.Common
Note: Currently, System.Drawing.Common is primarily supported on Windows. For cross-platform support, we recommend using Windows or Windows Server environments. Cross-platform graphics support is planned for future releases.
MIT License
Contributions are welcome! Please feel free to submit a Pull Request.
- Stamping: Overlay content on existing PDFs
- Redaction: Remove sensitive information
- PDF Optimization: Compress and optimize PDFs
- Page Numbering: Automatic page numbering
- Data Extraction: Extract structured data from PDFs
- Enhanced PDF parsing with full content stream support
- Complete XFA form flattening
- Full PDF/A validation and compliance
- OCR engine integration (Tesseract, etc.)
- Advanced typography (pdfCalligraph equivalent)
- Better HTML/CSS rendering with full CSS support
- Font embedding and subsetting
- Advanced encryption algorithms
For issues, questions, or contributions, please open an issue on GitHub.