惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
博客园_首页
IT之家
IT之家
Engineering at Meta
Engineering at Meta
量子位
宝玉的分享
宝玉的分享
MyScale Blog
MyScale Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
爱范儿
爱范儿
WordPress大学
WordPress大学
F
Full Disclosure
T
Tailwind CSS Blog
GbyAI
GbyAI
Recorded Future
Recorded Future
美团技术团队
S
SegmentFault 最新的问题
A
About on SuperTechFans
小众软件
小众软件
云风的 BLOG
云风的 BLOG
人人都是产品经理
人人都是产品经理
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
Apple Machine Learning Research
Apple Machine Learning Research
D
DataBreaches.Net
J
Java Code Geeks
The Cloudflare Blog
The GitHub Blog
The GitHub Blog
Hugging Face - Blog
Hugging Face - Blog
D
Docker
Vercel News
Vercel News
H
Help Net Security
博客园 - 叶小钗
B
Blog
阮一峰的网络日志
阮一峰的网络日志
N
Netflix TechBlog - Medium
Blog — PlanetScale
Blog — PlanetScale
腾讯CDC
Microsoft Security Blog
Microsoft Security Blog
V
Visual Studio Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
The Register - Security
The Register - Security
aimingoo的专栏
aimingoo的专栏
博客园 - 聂微东
月光博客
月光博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Last Week in AI
Last Week in AI
M
MIT News - Artificial intelligence
Jina AI
Jina AI

Inside Nutrient

A guide to the invisible work behind documents Introducing Nutrient Documents for Salesforce: Native document generation and signing Document AI vs. traditional OCR: Choosing between OCR, AI, and hybrid pipelines PDF SDK compliance and security evaluation checklist for enterprise teams (2026) Invariant Corp replaces paper processes with Nutrient Workflow and scales without limits What is process mapping? A complete guide Nutrient vs. Conga Composer for Salesforce document generation (2026) Document routing: How to automate document distribution The CTO’s AI playbook: Why accountability architecture beats orchestration Compliance workflow automation: Why built-in compliance is table stakes Workflow diagrams: Examples, symbols, and how to build one that actually runs Digital forms: Replace paper forms with automated workflows Approval workflow software: How to automate approvals Why document-centric automation is different The CEO’s AI playbook: Why decision architecture beats model selection Nutrient SDK product updates for Q1 2026 PDF redaction verification: How to prove sensitive data is permanently removed What is a VPAT? The complete guide to accessibility conformance reports What is PDF/UA? The accessible PDF standard explained Salesforce eSignatures: Generate, sign, and track documents in one flow Online document viewer: Options, tradeoffs, and how to embed one Document viewer for web apps: React, Vue, Angular (2026) Best document viewers in 2026: A buyer’s guide How to edit a PDF in Python: Add text, images, and annotations Nutrient advances Workflow platform with agentic AI for enterprise-grade speed and consistency in document-heavy operations How to create a Salesforce quote template from opportunity data The business case for accessibility: Five ways it drives enterprise value Python PDF library comparison (2026): 7 libraries for developers Why your AI agent hallucinates PDF table data PDF.js limitations: When to upgrade to a commercial PDF SDK How Subject scaled 5× with Nutrient’s PDF SDK without rebuilding its document layer I replaced our sales training with an AI coach that runs in Slack — here’s what broke Redirecting to: https://securitybuzz.com/cybersecurity-news/why-enterprise-permissions-are-ais-most-dangerous-inheritance/ Nutrient .NET SDK vs. iText Core: Complete comparison for .NET developers DocuVieware: Support’s most frequently asked setup questions Introducing Nutrient Workflow How to convert PDF to Word in C# (.NET) When email and spreadsheets stop working: Work order approval workflows for field teams on the move Compliance with confidence: Why document-centric automation is the foundation of your mission Nutrient expands AI Assistant, automating multistep document workflows inside any application What is document generation? A developer’s guide to PDF generation Document Converter data flow and how real-time watermarks skip the queue PDF/UA compliance guide: Requirements, standards, and best practices Computers still can’t understand you How Athena Intelligence built AI agents for regulated enterprises with Nutrient’s document infrastructure How to convert HTML to PDF (2026): 4 methods from browser print to SDK How to build a document extraction pipeline with Nutrient Vision API OCR vs. intelligent document processing: Choosing the right document extraction engine Beyond OCR: How document intelligence eliminates manual processing in regulated industries Nutrient vs. IronPDF: Complete comparison for .NET developers Nutrient vs. Aspose.PDF: Complete comparison for .NET developers Redirecting to: https://fortune.com/2026/02/19/openclaw-who-is-peter-steinberger-openai-sam-altman-anthropic-moltbook/ Lufthansa Systems uses Nutrient to deliver reliable, scalable PDF rendering for pilots worldwide Nutrient vs. Syncfusion: Complete comparison for .NET developers React’s useTransition: The hook you’re probably using wrong First City Monument Bank streamlines banking processes with Nutrient Workflow Redirecting to: https://www.sdcexec.com/warehousing/automation/article/22957364/nutrient-workflow-automation-the-missing-link-in-supply-chain-efficiency The complete guide to digital signatures: PAdES, CAdES, and XAdES explained Nutrient Python SDK: Production-grade document processing for Python Introducing agentic document editing for web applications with AI Assistant Nutrient vs. QuestPDF: Complete comparison for .NET developers How we fixed the GdPicture license expiration (and what to do if you’re affected) Red team security testing with agentic AI The future of healthcare document automation Best healthcare workflow software compared Nutrient SDK product updates for Q4 2025 How Harvey scaled legal document workflows 50 percent MoM without rebuilding infrastructure HIPAA-compliant document management in hospitals How we optimized rendering performance while handling thousands of annotations in React — Part 2 Automated PII removal with Nutrient API Redirecting to: https://www.devopsdigest.com/2026-low-code-no-code-predictions Redirecting to: https://www.kmworld.com/Articles/Editorial/ViewPoints/Leaders-predict-AI-to-continue-permeating-all-aspects-of-KM-in-2026-172594.aspx What are deep agents and how do they solve complex problems? Whipping up document magic: Your easy-bake recipe for Vue and Nutrient Web SDK 🧁 What I’ve learned about product iteration planning while building SDKs Passwordless document signing: Three-layer security guide New zip folder functionality streamlines file management in Document Automation Server The keyboard shortcuts playbook: Taking control of keyboard events in Nutrient Web SDK From experienced engineer to AI beginner: My unexpected journey AI-assisted manual testing: Handling Safari’s PDF rendering and UI quirks How to keep a 20-year-old SDK up to date How we optimized rendering performance while handling thousands of annotations in React — Part 1 Nutrient announces new executive hires to accelerate next phase of growth High performance UI using web workers Automate document conversion at scale with Python and Nutrient DCS From curiosity to PLG (and AI): My journey to understanding product-led growth Prost to progress: One year as Nutrient Pigeon usage at Nutrient: Bridging native SDKs to Flutter Modernizing CI build servers: How to migrate from Chef to Ansible Unix man pages: AI-friendly documentation since 1971 Consistent hashing for even load distribution Best AI redaction APIs: Complete comparison guide for 2025 Why AI document redaction matters for modern security From coding to coordinating: How AI transformed my workflow What is intelligent document processing (IDP)? A complete guide Enterprise PDF SDKs: Best PSPDFKit (now Nutrient) alternatives Nutrient SDK product updates for Q3 2025 GdPicture support best practices Redacting sensitive data with Nutrient AI redaction API How AI is transforming the customer experience at Nutrient: From instant answers to intelligent support
How to generate a PDF in Blazor with PDFsharp
Hulya Masharipov · 2024-05-24 · via Inside Nutrient

Updated: October 21, 2024

Table of contents

    How to generate a PDF in Blazor with PDFsharp

    Summary

    Learn how to build a Blazor Server PDF generator using the PDFsharp library to create and download PDF documents dynamically. This comprehensive tutorial demonstrates setting up a .NET project, integrating PDFsharp for PDF creation, implementing JavaScript interop for file downloads, and creating a user-friendly interface. Discover how Nutrient’s .NET PDF library offers advanced features like OCR, barcode processing, and comprehensive PDF editing capabilities for enterprise applications.

    Blazor Server applications offer a dynamic way to work with web technologies using C# and .NET. In this blog post, we’ll demonstrate how to generate a simple PDF in a Blazor Server application using the PDFsharp(opens in a new tab) library. Additionally, you’ll learn about Nutrient’s .NET PDF library, which offers more advanced features for complex .NET projects.

    PDFsharp(opens in a new tab) is a .NET library for processing PDF files, and it can be integrated into a Blazor project for this purpose.

    Prerequisites

    Step 1 — Setting up the Blazor Server project

    Open Visual Studio Code and create a new directory for your project. In your terminal, navigate to the project directory and run the following command to create a Blazor Server project:

    dotnet new blazorserver -n GeneratePDFBlazor

    After the project is created, open the project folder in Visual Studio Code:

    Next, restore the project dependencies:

    Your project must be .NET 6 or higher, as the .NET Framework is no longer supported.

    Step 2 — Installing the PDFsharp package

    Now, install the PDFsharp package using the .NET CLI:

    dotnet add package PDFsharp --version 6.0.0

    Alternatively, you can add PDFsharp by modifying the GeneratePDFBlazor.csproj file. Add the following under the <ItemGroup> section:

    <PackageReference Include="PDFsharp" Version="6.0.0" />

    Then run:

    Step 3 — Setting up the PDF generator

    Now, create a new class named PdfGenerator.cs in the GeneratePDFBlazor project folder. This class will handle the creation of the PDF document using PDFsharp. In Visual Studio Code, create a new file, PdfGenerator.cs, and add the following code:

    using PdfSharp;

    using PdfSharp.Pdf;

    using PdfSharp.Drawing;

    using PdfSharp.Fonts;

    using PdfSharp.Snippets.Font;

    public class PdfGenerator

    {

    public static byte[] CreatePdf()

    {

    using (var memoryStream = new MemoryStream())

    {

    if (Capabilities.Build.IsCoreBuild)

    GlobalFontSettings.FontResolver = new FailsafeFontResolver();

    PdfDocument document = new PdfDocument();

    document.Info.Title = "Generated with PDFsharp";

    PdfPage page = document.AddPage();

    XGraphics gfx = XGraphics.FromPdfPage(page);

    var width = page.Width;

    var height = page.Height;

    gfx.DrawLine(XPens.Red, 0, 0, width, height);

    gfx.DrawLine(XPens.Red, width, 0, 0, height);

    var radius = width / 5;

    gfx.DrawEllipse(new XPen(XColors.Red, 1.5), XBrushes.White, new XRect(width / 2 - radius, height / 2 - radius, 2 * radius, 2 * radius));

    XFont font = new XFont("Times New Roman", 20, XFontStyleEx.BoldItalic);

    gfx.DrawString("Hello, PDFsharp!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);

    document.Save(memoryStream);

    return memoryStream.ToArray();

    }

    }

    }

    This class generates a simple PDF with text and graphics using PDFsharp and returns it as a byte array.

    Step 4 — Creating the Blazor interface

    Next, you’ll create a user interface in Blazor to generate and download the PDF. Open the Pages/Index.razor file and update it as follows:

    @page "/"

    @inject IJSRuntime JSRuntime

    <h3>PDF Generator</h3>

    <button class="btn btn-primary" @onclick="DownloadPdf">Download PDF</button>

    @code {

    private async Task DownloadPdf()

    {

    byte[] pdfBytes = PdfGenerator.CreatePdf();

    var fileName = "GeneratedPdf.pdf";

    await JSRuntime.InvokeVoidAsync("saveAsFile", fileName, Convert.ToBase64String(pdfBytes));

    }

    }

    The DownloadPdf method calls the PdfGenerator.CreatePdf method. It then uses JavaScript interop to trigger a download in the browser.

    JavaScript interop in _Host.cshtml

    Finally, add the JavaScript required for downloading the PDF in the Pages/_Host.cshtml file. Add the following script before the closing body tag:

    <script>

    window.saveAsFile = (filename, bytesBase64) => {

    var link = document.createElement("a");

    link.href = "data:application/octet-stream;base64," + bytesBase64;

    link.download = filename;

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);

    };

    </script>

    This script creates a temporary link element, sets its href to the base64-encoded PDF data, and triggers a click to start the download.

    Step 5 — Running the application

    In Visual Studio Code, open the terminal and run the following command:

    By default, the application may run on a different port (e.g. http://localhost:5138). You can access the application by going to http://localhost:5138 in your browser.

    You’ll see the interface you created, and clicking the Download PDF button will generate and download the PDF.

    Step 6 — Interacting with the application

    Interact with your application in the browser. Click the button (or perform the action you set up) to trigger the PDF generation. The PDF will be generated and then downloaded by the browser.

    interface

    result

    The PDFsharp library offers a wide range of capabilities for creating complex PDFs, while Blazor and JavaScript interop make it easy to deliver these documents to your users. This basic setup can be expanded and customized to meet the specific needs of your application.

    You can find the full source code for this tutorial in our GitHub repository.(opens in a new tab)

    Nutrient .NET SDK

    While both PDFsharp and the Nutrient .NET SDK offer PDF generation capabilities for .NET applications, Nutrient .NET SDK stands out as a more comprehensive and feature-rich solution. Here are some reasons why Nutrient .NET SDK can be considered better:

    1. Extensive capabilities — Nutrient .NET SDK provides a wide range of functionalities, including OCR, barcode processing, PDF editing, document conversion, scanning, and image processing. It outperforms many other .NET document imaging technologies available on the market.
    2. OCR (optical character recognition) — Nutrient .NET SDK supports OCR, which enables the extraction of text from scanned documents and images. This feature is essential for applications that require text recognition and data extraction from PDFs.
    3. Advanced PDF editing — Nutrient’s PDF editor SDK offers more advanced PDF editing capabilities, such as editing text, images, and annotations, as well as adding watermarks, digital signatures, and form fields to PDF documents.
    4. Comprehensive support — Nutrient has a reputation for providing excellent customer support and regular updates to address any issues or introduce new features. This ensures that your application remains up to date and well-maintained.
    5. Integration-friendly — Nutrient .NET SDK is designed to seamlessly integrate into your existing .NET applications, making it easier to adopt and implement in your projects.
    6. Documentation and resources — Nutrient offers comprehensive documentation, tutorials, and sample code, making it easier for developers to get started and leverage the library’s full potential.

    To get started with the Nutrient .NET SDK, follow our getting started guide.

    Conclusion

    This tutorial demonstrated how to use the PDFsharp library for basic PDF generation in Blazor Server applications. PDFsharp is an excellent open source tool for creating and manipulating PDFs in .NET, ideal for straightforward tasks like drawing text and graphics in documents.

    For more advanced features, however, consider the Nutrient .NET SDK library. It extends capabilities to include OCR, PDF editing, barcode processing, and document conversion. This makes it a comprehensive solution for complex Blazor projects that require robust document processing functionalities. Whether you need simplicity with PDFsharp or advanced features with GdPicture.NET, both libraries offer powerful ways to handle PDFs in Blazor applications.

    To see a list of all frameworks, you can contact our Sales team. Or, launch our demo to see our viewer in action.

    FAQ

    PDFsharp offers an easy way to generate PDFs directly from C# code, making it ideal for Blazor Server applications.

    No, PDFsharp is not compatible with Blazor WebAssembly due to its reliance on server-side .NET features.

    For large PDFs, it’s recommended to generate the file in chunks or stream the content to optimize performance and reduce memory usage.

    No, PDFsharp is primarily used for creating new PDFs, not for editing or manipulating existing ones.

    Yes, PDFsharp allows full customization of fonts, colors, and page layout, giving you control over a PDF’s appearance.

    Explore related topics

    Try for free Ready to get started?

    Related SDK articles

    Explore more