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

推荐订阅源

L
LINUX DO - 最新话题
Apple Machine Learning Research
Apple Machine Learning Research
月光博客
月光博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The GitHub Blog
The GitHub Blog
爱范儿
爱范儿
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
美团技术团队
WordPress大学
WordPress大学
F
Fortinet All Blogs
IT之家
IT之家
阮一峰的网络日志
阮一峰的网络日志
云风的 BLOG
云风的 BLOG
F
Full Disclosure
博客园 - 三生石上(FineUI控件)
Microsoft Azure Blog
Microsoft Azure Blog
U
Unit 42
博客园 - 【当耐特】
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
V
Visual Studio Blog
P
Proofpoint News Feed
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LangChain Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
Secure Thoughts
www.infosecurity-magazine.com
www.infosecurity-magazine.com
H
Heimdal Security Blog
W
WeLiveSecurity
Cloudbric
Cloudbric
N
News and Events Feed by Topic
Last Week in AI
Last Week in AI
N
News and Events Feed by Topic
G
Google Developers Blog
Attack and Defense Labs
Attack and Defense Labs
Google Online Security Blog
Google Online Security Blog
S
Security Affairs
S
Security @ Cisco Blogs
雷峰网
雷峰网
有赞技术团队
有赞技术团队
Webroot Blog
Webroot Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
C
Cyber Attacks, Cyber Crime and Cyber Security
Spread Privacy
Spread Privacy
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Engineering at Meta
Engineering at Meta
P
Palo Alto Networks Blog
D
DataBreaches.Net
Application and Cybersecurity Blog
Application and Cybersecurity Blog

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 Use PDFsharp and Blazor to Edit PDFs
Hulya Masharipov · 2024-05-23 · via Inside Nutrient

Table of contents

    How to Use PDFsharp and Blazor to Edit PDFs

    Editing PDFs in a Blazor application requires a reliable and efficient tool. PDFsharp(opens in a new tab), an open source .NET library, is a perfect candidate for editing PDFs. In the first part of this blog post, we’ll guide you through setting up a Blazor project in Visual Studio and implementing PDF editing using PDFsharp. In the second part, you’ll learn how to edit PDFs using PSPDFKit’s Blazor PDF library, which provides an extensive set of features for working with PDFs in a Blazor application.

    Prerequisites

    Setting Up Your Blazor Project with Visual Studio

    Before diving into PDF editing functionalities, you’ll set up a Blazor Server project in Visual Studio.

    • To create a new project for your application, open Visual Studio and select File > New Project….

    project setup

    • Choose the Blazor Server App project template. Press Continue.

    project setup

    • Choose .NET 7.0 for the target framework. Press Continue.

      project setup

    • When prompted, choose your app name (EditPDFBlazor), and use the default options. Then press Create.

    project setup

    For platform-specific instructions (Windows/Linux/macOS), refer to the Microsoft documentation(opens in a new tab) on creating a Blazor Server App.

    Adding PDFsharp to Your Project

    Once your project is created, go to the Solution Explorer. Right-click on your project and choose Manage NuGet Packages…. Click the Browse tab, search for PDFsharp, and install it.

    nuget

    Implementing PDF Editing with PDFsharp

    Now that your project is set up, you’ll implement the PDF editing functionality.

    Adding the PdfEditor Class

    • Right-click on your project in Solution Explorer.
    • Choose Add > New Class… and name it PdfEditor.cs.
    • Implement the editing logic in your PdfEditor.cs(opens in a new tab) file:

    using PdfSharp.Pdf;

    using PdfSharp.Pdf.IO;

    using PdfSharp.Drawing;

    using PdfSharp.Fonts;

    using PdfSharp.Snippets.Font;

    using PdfSharp;

    public class PdfEditor

    {

    static PdfEditor()

    {

    if (Capabilities.Build.IsCoreBuild)

    GlobalFontSettings.FontResolver = new FailsafeFontResolver();

    }

    public void EditPdf(string filePath)

    {

    PdfDocument document = PdfReader.Open(filePath, PdfDocumentOpenMode.Modify);

    PdfPage page = document.Pages[0];

    XGraphics gfx = XGraphics.FromPdfPage(page);

    XFont font = new XFont("Verdana", 20, XFontStyleEx.Bold);

    gfx.DrawString("Added this with PDFsharp", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.TopLeft);

    document.Save(filePath);

    }

    }

    In the static constructor, set the font resolver, ensuring that this setup runs only once when the class is first used. The EditPdf method opens a specified PDF file, adds text to the first page, and saves the changes.

    Updating the Razor Component

    Open the Index.razor(opens in a new tab) file from the Pages directory. Inject the PdfEditor class and add a button to trigger PDF editing:

    @page "/"

    @inject PdfEditor pdfEditor

    <button class="btn btn-primary" @onclick="EditPdfDocument">Edit PDF</button>

    @code {

    private void EditPdfDocument()

    {

    pdfEditor.EditPdf("wwwroot/document.pdf"); // Add your PDF file to the wwwroot directory

    }

    }

    Clicking this button calls EditPdfDocument, which in turn uses PdfEditor to edit the specified PDF file.

    Make sure to add your PDF file to the wwwroot directory. You can use our demo document as an example.

    Configuring the PdfEditor Service

    Add the PdfEditor class as a singleton service in the Program.cs(opens in a new tab) of your Blazor application:

    // Add `PdfEditor` as a singleton service.

    builder.Services.AddSingleton<PdfEditor>();

    Registering PdfEditor as a singleton ensures that it’s available throughout the application’s lifecycle.

    Running Your Application

    Press F5, or click Start in Visual Studio to run your application. Once running, navigate to the main page and click the Edit PDF button to test your PDF editing functionality. Or, you can run the following command in the terminal:

    resulting pdf

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

    PSPDFKit Blazor PDF Viewer

    We offer a commercial Blazor PDF viewer library that can easily be integrated into your web application. It comes with 30+ features that let you view, annotate, edit, and sign documents directly in your browser. Out of the box, it has a polished and flexible UI that you can extend or simplify based on your unique use case.

    • A prebuilt and polished UI for an improved user experience
    • 15+ prebuilt annotation tools to enable document collaboration
    • Support for more file types with client-side PDF, MS Office, and image viewing
    • Dedicated support from engineers to speed up integration

    If you prefer a video tutorial, you can watch our step-by-step guide below. Otherwise, keep reading.

    YouTube video player

    Creating a New Blazor WASM Project

    1. For this tutorial, you’ll install the Blazor WebAssembly template using the .NET CLI(opens in a new tab) (command-line interface). Open your terminal, navigate to the directory you want to create your project in, and run the following command:

    dotnet new blazorwasm -o PSPDFKit_BlazorWASM

    This command creates your new Blazor app project and places it in a new directory inside your current location called PSPDFKit_BlazorWASM.

    1. Change your directory into the newly created project:

    blazorwasm is a template that creates the initial files and directory structure for a Blazor WebAssembly project.

    Adding PSPDFKit to Your Project

    PSPDFKit for Web library files are distributed as an archive that can be extracted manually.

    1. Download the framework here(opens in a new tab). The download will start immediately and will save a .tar.gz archive like PSPDFKit-Web-binary-2022.2.1.tar.gz to your computer.
    2. Once the download is complete, extract the archive and copy the entire contents of its dist folder to your project’s wwwroot folder.
    3. Make sure your wwwroot folder contains the pspdfkit.js file and a pspdfkit-lib directory with the library assets.

    Displaying a PDF

    1. Add the PDF document you want to display to the wwwroot directory. You can use our demo document as an example.
    2. Navigate to the Shared/MainLayout.razor file. The layout component inherits from LayoutComponentBase(opens in a new tab), and it adds a @Body(opens in a new tab) property to the component, which contains the content to be rendered inside the layout. During rendering, the @Body property will be replaced with the content of the layout:

    @inherits LayoutComponentBase

    @Body

    1. Now you’ll start working on the Home route. Navigate to your project’s Pages/index.razor file, and replace the contents of the file with the following:

    @page "/"

    @inject IJSRuntime JS

    <div id='container' style='background: gray; width: 100vw; height: 100vh; margin: 0 auto;'></div>

    @code {

    protected override async void OnAfterRender(bool firstRender)

    {

    if (firstRender) {

    await JS.InvokeVoidAsync("loadPDF", "#container", "document.pdf");

    }

    }

    }

    Here, the @page directive is pointing to the Home (/) route.

    To invoke JavaScript functions from .NET, inject the IJSRuntime(opens in a new tab) abstraction and call the InvokeVoidAsync(opens in a new tab) method, which doesn’t return a value.

    The div element is used to display the PDF document.

    1. Load the PSPDFKit SDK loading code to wwwroot/index.html before the </body> tag:

    <script src="dist/pspdfkit.js"></script>

    <script>

    function loadPDF(container, document) {

    PSPDFKit.load({

    container,

    document,

    });

    }

    </script>

    Serving the Application

    1. Start the app in the root directory of your project:

    terminal

    If you get a prompt asking for permissions, type your keychain and click Always Allow.

    The server will start and will automatically restart when changes are made to the project.

    pspdfkit demo

    You can access the source code for this tutorial on GitHub(opens in a new tab); just navigate to the wasm folder. If you’re looking for the Blazor Server example, you can find the example project under the server folder or follow our getting started guide here.

    PDF Editing with PSPDFKit for Blazor

    This next section outlines how to edit documents using PSPDFKit for Blazor.

    Editing Text in a PDF Document

    To enable content editing in the PSPDFKit instance after loading the document, modify your loadPDF JavaScript function to set the interaction mode to PSPDFKit.InteractionMode.CONTENT_EDITOR using the setViewState method:

    <script>

    function loadPDF(container, document) {

    PSPDFKit.load({

    container,

    document,

    }).then((instance) => {

    instance.setViewState((v) =>

    v.set(

    'interactionMode',

    PSPDFKit.InteractionMode.CONTENT_EDITOR,

    ),

    );

    return instance;

    });

    }

    </script>

    This function will load the PDF document and immediately switch the interaction mode to content editing mode when the document finishes loading.

    Page Manipulation

    This next section will cover different ways of manipulating pages in PDFs.

    Rotating PDF Pages

    To perform page rotation in PSPDFKit within your Blazor application, you’ll need to define an operations object with the following properties:

    • type — Indicates the type of operation you want to execute.
    • pageIndexes — Specifies which page or pages you intend to rotate.
    • rotateBy — Sets the angle by which you want to rotate the page.

    Only multiples of 90, up to 360, are allowed as values.

    Here’s an example of how to structure the operations object:

    {

    type: "rotatePages",

    pageIndexes: [0], // This will rotate page 1.

    rotateBy: 90 // Rotate the page 90 degrees clockwise.

    }

    To apply this operation, pass the operations object to the PSPDFKit.Instance.applyOperations method:

    <script>

    function loadPDF(container, document) {

    PSPDFKit.load({

    container,

    document,

    }).then((instance) => {

    // Define the rotation operation.

    const rotationOperation = {

    type: 'rotatePages',

    pageIndexes: [0], // Rotate page 1.

    rotateBy: 90, // Rotate page 90 degrees clockwise.

    };

    // Apply the rotation operation.

    instance.applyOperations([rotationOperation]);

    return instance;

    });

    }

    </script>

    rotate pdf

    Cropping PDFs

    You can crop specific pages within a PDF document using the PSPDFKit library in your Blazor application. To perform cropping, you’ll need to define an operations object with the following properties:

    • type — Specifies the type of operation you wish to perform.
    • pageIndexes — Targets the page or pages you want to crop.
    • cropBox — Defines the crop window as a rectangle.

    Here’s an example of how to structure the operations object for cropping:

    {

    type: "cropPages",

    pageIndexes: [1, 2], // Crop pages 2 and 3 (0-based index).

    cropBox: new PSPDFKit.Geometry.Rect({

    left: 10,

    top: 10,

    width: 100,

    height: 100

    })

    }

    To apply this cropping operation, pass the operations object to the PSPDFKit.Instance.applyOperations method, as demonstrated below:

    <script>

    function loadPDF(container, document) {

    return PSPDFKit.load({

    container,

    document,

    }).then((instance) => {

    // Define the cropping operation.

    const croppingOperation = {

    type: 'cropPages',

    pageIndexes: [1, 2], // Crop pages 2 and 3 (0-based index).

    cropBox: new PSPDFKit.Geometry.Rect({

    left: 10,

    top: 10,

    width: 100,

    height: 100,

    }),

    };

    // Apply the cropping operation.

    instance.applyOperations([croppingOperation]);

    return instance;

    });

    }

    </script>

    crop pdfs

    If you omit the pageIndexes property from the code above, all the PDF document’s pages will be cropped.

    Moving a Page within a Document

    Move a page using the following operations object definition:

    • type — The type of operation you want to perform.
    • pageIndexes — Targets the page(s) you want to move.
    • beforePageIndex — Moves the targeted page(s) before the page specified here.
    • afterPageIndex — Moves the targeted page(s) after the page specified here.

    Here’s an example of how to structure the operations object for page movement:

    {

    type: "movePages",

    pageIndexes: [0, 4], // Move pages 1 and 5.

    afterPageIndex: 3 // The specified pages will be moved after page 3.

    }

    Apply this configured operations object by passing it to the PSPDFKit.Instance.applyOperations method:

    <script>

    function loadPDF(container, document) {

    return PSPDFKit.load({

    container,

    document,

    }).then(async (instance) => {

    // Define the page movement operation.

    const pageMovementOperation = {

    type: 'movePages',

    pageIndexes: [0, 4], // Move pages 1 and 5.

    afterPageIndex: 3, // Move the specified pages after page 3.

    };

    // Apply the page movement operation.

    await instance.applyOperations([pageMovementOperation]);

    return instance;

    });

    }

    </script>

    Copying a Page

    To copy a page/pages, define the operations object like so:

    • type — The type of operation you want to perform (in this case, duplicating pages).
    • pageIndexes — Targets the page(s) you want to duplicate and inserts each duplicate after the original page.

    {

    type: "duplicatePages",

    pageIndexes: [0, 4] // Duplicate pages 1 and 5, inserting each duplicate after the original page.

    }

    Apply these copying instructions by passing the operations object to the PSPDFKit.Instance.applyOperations method:

    <script>

    function loadPDF(container, document) {

    return PSPDFKit.load({

    container,

    document,

    }).then(async (instance) => {

    // Define the page copying operation.

    const pageCopyingOperation = {

    type: 'duplicatePages',

    pageIndexes: [0, 4], // Duplicate pages 1 and 5, inserting each duplicate after the original page.

    };

    // Apply the page copying operation.

    await instance.applyOperations([pageCopyingOperation]);

    return instance;

    });

    }

    </script>

    Removing Pages from a PDF

    You can remove pages from a PDF using the following operations object definition:

    • type — The type of operation you want to perform (in this case, removing pages). The keepPages type keeps the pages specified using pageIndexes. The opposite can be achieved with the removePages type.
    • pageIndexes — Targets the page(s) you want to remove or keep.

    {

    type: "removePages",

    pageIndexes: [0, 1, 2] // Remove pages 1, 2, and 3.

    }

    Apply these removal instructions by passing the operations object to the PSPDFKit.Instance.applyOperations method:

    <script>

    function loadPDF(container, document) {

    return PSPDFKit.load({

    container,

    document,

    }).then(async (instance) => {

    // Define the page-removing operation.

    const pageRemovingOperation = {

    type: 'removePages',

    pageIndexes: [0, 1, 2], // Remove pages 1, 2, and 3.

    };

    // Apply the page-removing operation.

    await instance.applyOperations([pageRemovingOperation]);

    return instance;

    });

    }

    </script>

    Adding a Page to a PDF Document

    To add a page to a document, define the operations object like so:

    • type — The type of operation you want to perform.
    • afterPageIndex — The new page is added after the index specified here.
    • backgroundColor — Applies a background color to the new page.
    • pageWidth — Width of the new page.
    • pageHeight — Height of the new page.
    • rotateBy — Rotation for the new page.

    Here’s an example of how to structure the operations object for adding a page:

    {

    type: "addPage",

    afterPageIndex: 1, // Add a new page after page 2.

    backgroundColor: new PSPDFKit.Color({ r: 100, g: 200, b: 255 }), // Set the new page background color.

    pageWidth: 750,

    pageHeight: 1000,

    rotateBy: 0 // No rotation.

    }

    Apply these addition instructions by passing the operations object to the PSPDFKit.Instance.applyOperations method:

    <script>

    function loadPDF(container, document) {

    return PSPDFKit.load({

    container,

    document,

    }).then(async (instance) => {

    // Define the page addition operation.

    const pageAdditionOperation = {

    type: 'addPage',

    afterPageIndex: 1, // Add a new page after page 2.

    backgroundColor: new PSPDFKit.Color({

    r: 100,

    g: 200,

    b: 255,

    }), // Set the new page background color (optional).

    pageWidth: 750,

    pageHeight: 1000,

    rotateBy: 0, // No rotation.

    };

    // Apply the page addition operation.

    await instance.applyOperations([pageAdditionOperation]);

    return instance;

    });

    }

    </script>

    adding a page

    With this modification, the loadPDF function will now perform a page addition operation. It’ll add a new page after page 2 with the specified settings, including background color, page dimensions, and rotation.

    Adding Images to a PDF Document

    You can add images to your document using the image annotation API.

    1. Fetch the image you want to include in your PDF and convert it into a Blob. You can use the fetch API to do this:

    const request = await fetch('https://picsum.photos/200');

    const blob = await request.blob();

    1. Utilize the instance#createAttachment method to transform the image Blob into an attachment, effectively storing the image within your PDF:

    const imageAttachmentId = await instance.createAttachment(blob);

    1. To display this image attachment within the PDF document, create an image annotation. Configure the annotation with the following properties:
    • pageIndex — Specify the page index where you want to place the image.
    • contentType — Define the image’s content type (e.g. JPEG).
    • imageAttachmentId — Attach the image using the attachment ID obtained earlier.
    • description — Provide a description for the image.
    • boundingBox — Specify the position and dimensions of the image on the page.

    const annotation = new PSPDFKit.Annotations.ImageAnnotation({

    pageIndex: 0, // Page index where you want to add the image.

    contentType: 'image/jpeg', // Image content type (e.g. JPEG).

    imageAttachmentId, // Attach the image using the attachment ID.

    description: 'Example Image Annotation', // Description for the image.

    boundingBox: new PSPDFKit.Geometry.Rect({

    left: 10,

    top: 20,

    width: 200,

    height: 200,

    }), // Position and dimensions of the image on the page.

    });

    Finally, create the image annotation within the PDF using the instance.create method:

    instance.create(annotation);

    Here’s the complete code for adding an image to a PDF document:

    <script>

    async function loadPDF(container, document) {

    const instance = await PSPDFKit.load({

    container,

    document,

    });

    // Fetch the image you want to add to the PDF.

    const request = await fetch('https://picsum.photos/200');

    const blob = await request.blob();

    // Convert the image into an attachment in the PDF.

    const imageAttachmentId = await instance.createAttachment(blob);

    // Create an image annotation with the desired properties.

    const annotation = new PSPDFKit.Annotations.ImageAnnotation({

    pageIndex: 0, // Specify the page index where you want to add the image.

    contentType: 'image/jpeg', // Specify the image content type (e.g. JPEG).

    imageAttachmentId, // Attach the image using the attachment ID.

    description: 'Example Image Annotation', // Provide a description for the image.

    boundingBox: new PSPDFKit.Geometry.Rect({

    left: 10,

    top: 20,

    width: 200,

    height: 200,

    }), // Define the position and dimensions of the image on the page.

    });

    // Create the image annotation.

    instance.create(annotation);

    return instance;

    }

    </script>

    adding an image to pdf

    Editing Page Labels in a PDF

    To edit a page label, define the operations object like so:

    • type — The type of operation you want to perform.
    • pageIndexes — Targets the page(s) for label editing.
    • pageLabel — Defines the label.

    {

    type: "setPageLabel",

    pageIndexes: [0], // Target page index 0 for label editing.

    pageLabel: "New page label" // Define the new page label.

    }

    Apply the label editing operation to your PDF document using the instance.applyOperations method:

    instance.applyOperations([

    {

    type: 'setPageLabel',

    pageIndexes: [0],

    pageLabel: 'New page label',

    },

    ]);

    Here’s the code for editing a page label in your PDF document using PSPDFKit for Blazor:

    <script>

    async function loadPDF(container, document) {

    const instance = await PSPDFKit.load({

    container,

    document,

    });

    // Define the page label editing operation.

    const pageLabelEditingOperation = {

    type: 'setPageLabel',

    pageIndexes: [0], // Specify the page index for label editing (e.g. page 1).

    pageLabel: 'New page label', // Define the new page label.

    };

    // Apply the page label editing operation.

    await instance.applyOperations([pageLabelEditingOperation]);

    return instance;

    }

    </script>

    Splitting a PDF Document

    To split a PDF document into two separate PDFs in a Blazor WebAssembly application, follow the steps outlined below.

    1. Create a JavaScript utility file (downloadUtils.js) in the wwwroot directory.

    In this file, define a utility function called downloadPdf. This function will handle the download of PDF files. Here’s an explanation of the function:

    // Create a utility function to handle PDF downloads.

    function downloadPdf(blob) {

    const a = document.createElement('a');

    a.href = window.URL.createObjectURL(blob);

    a.download = 'split_document.pdf';

    a.style.display = 'none';

    document.body.appendChild(a);

    a.click();

    document.body.removeChild(a);

    }

    The downloadPdf function creates an anchor element (<a>) to facilitate the download of a PDF file. It sets the href attribute to the URL of the PDF data, assigns a download attribute to specify the file name, and handles the download process.

    1. Include the downloadUtils.js file in your wwwroot/index.html file:

    <script src="downloadUtils.js"></script>

    Then, define a Blazor JavaScript function named loadPDF. This function loads the PDF document using PSPDFKit, applies the page-removal operation to split the document, exports the resulting PDF, and uses the downloadPdf function to make the split document available for download:

    <script>

    async function loadPDF(container, document) {

    const instance = await PSPDFKit.load({

    container,

    document,

    headless: true,

    });

    // Define the page-removal operation to split the document.

    const pageRemovalOperation = {

    type: 'removePages',

    pageIndexes: [2, 3, 4], // Remove pages 3, 4, and 5 to split the document.

    };

    // Apply the page-removal operation and export the resulting PDF.

    const buffer = await instance.exportPDFWithOperations([

    pageRemovalOperation,

    ]);

    // Convert the PDF buffer into a downloadable file using the utility function.

    downloadPdf(new Blob([buffer], { type: 'application/pdf' }));

    return instance;

    }

    </script>

    In this Blazor code, call the downloadPdf function from the JavaScript utility file after performing the PSPDFKit operations. This approach allows you to encapsulate the DOM-related download functionality in JavaScript, where it’s permitted, and then invoke it from your Blazor code.

    Conclusion

    PDF editing in Blazor with PDFsharp is a straightforward process, especially for basic modifications like adding text or images. PDFsharp is a versatile open source library for creating and manipulating PDF documents in C#, while PSPDFKit provides a commercial Blazor PDF viewer with advanced features for working with PDFs in a web application.

    To learn more about PSPDFKit for Web, start your free trial. Or, launch our demo to see our viewer in action.

    Explore related topics

    Try for free Ready to get started?

    Related SDK articles

    Explore more