diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-Document-in-Azure.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-Document-in-Azure.md index 59588aa9f9..11f6680dc7 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-Document-in-Azure.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-Document-in-Azure.md @@ -6,19 +6,525 @@ control: PDF documentation: UG --- -# Create PDF document in Azure platform +# Create a PDF File in Microsoft Azure -The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, edit PDF documents programmatically without the dependency of **Adobe Acrobat**. Using this library, **create a PDF document in Azure services** within a few lines of code. +The [Syncfusion .NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create, read, and edit PDF documents programmatically without requiring Adobe Acrobat. This guide demonstrates how to generate PDF documents in Azure cloud services using C# and .NET. -N> If this is your first time working with Azure, please refer to the dedicated Azure development resources. This section explains how to create a PDF document in C# using the .NET PDF library in Azure. +> **Note**: This guide assumes basic familiarity with Azure portal and .NET development. For comprehensive Azure fundamentals, refer to the [Microsoft Azure Learning Path](https://learn.microsoft.com/en-us/training/azure/). -## Prerequisites +## Prerequisites -* An active **Microsoft Azure subscription** is required. If you don't have one, please create a free account before starting. -* Install the required NuGet package: [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core/). +| Item | Details | +| --- | --- | +| **Azure Subscription** | Active Microsoft Azure subscription (free tier eligible) | +| **Development Environment** | Visual Studio 2022 or Visual Studio Code with C# extension | +| **.NET Version** | .NET 6.0 or later (.NET 8.0 recommended) | +| **NuGet Package** | Syncfusion.Pdf.NET (latest version from NuGet.org) | +| **License** | Syncfusion license key (required for production deployments) | +| **Azure CLI** | Optional but recommended for deployment automation | + +To include the .NET PDF library in your Azure project, refer to the [NuGet Package Requirements](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) documentation. ## Supported Azure Services -* Azure App Service (Windows & Linux) -* Azure Functions -* Azure Functions in AKS (Azure Kubernetes Service) +The Syncfusion PDF library supports multiple Azure hosting options, each with distinct benefits: + +| Service | Scenario | Scaling | Cost Model | +|---------|----------|---------|-----------| +| **Azure App Service** | Traditional web apps, APIs, long-running processes | Manual or auto-scale | Pay per instance | +| **Azure Functions** | Event-triggered, on-demand PDF generation, periodic jobs | Automatic | Pay per execution | +| **Azure Container Instances (ACI)** | Containerized applications, microservices | Automatic | Pay per second | +| **Azure Kubernetes Service (AKS)** | Large-scale, multi-container deployments, enterprise workloads | Orchestrated | Pay per node | +| **Azure App Service for Containers** | Container-based web apps with managed scaling | Auto-scale | Pay per instance | + +### Recommended Selection Guide + +- **New to cloud? Choose Azure App Service** — Simplest setup with built-in scaling and monitoring +- **Serverless/on-demand? Choose Azure Functions** — Pay only for execution time, auto-scales to zero +- **Enterprise deployment? Choose AKS** — Full control, Kubernetes orchestration, advanced networking +- **Containerized apps? Choose Container Instances** — Quick deployment without infrastructure management + +## Architecture Overview + +``` +┌─────────────────────────────────────────────┐ +│ Client Application │ +│ (Web browser, mobile app, desktop app) │ +└──────────────────┬──────────────────────────┘ + │ HTTP/HTTPS Request + ▼ +┌─────────────────────────────────────────────┐ +│ Azure Hosting Service │ +│ (App Service | Functions | AKS) │ +│ ┌───────────────────────────────────────┐ │ +│ │ ASP.NET Core Web API / Function │ │ +│ │ ┌─────────────────────────────────┐ │ │ +│ │ │ Syncfusion PDF Library │ │ │ +│ │ │ - Create PDF from data │ │ │ +│ │ │ - Apply styling & formatting │ │ │ +│ │ │ - Handle licensing │ │ │ +│ │ └─────────────────────────────────┘ │ │ +│ └───────────────────────────────────────┘ │ +│ │ │ +│ ┌────────────────┼────────────────┐ │ +│ ▼ ▼ ▼ │ +│ Blob Storage SQL Database Memory │ +│ (PDF files) (Metadata) (Stream) │ +└──────────────────┬────────────────────────┘ + │ PDF Output + ▼ + ┌──────────────────┐ + │ Client Downloads│ + │ PDF File │ + └──────────────────┘ +``` + +## Creating PDF Documents in Azure App Service + +Azure App Service is the recommended starting point for most PDF generation workloads. This section provides a complete implementation guide. + +### Step 1: Create an ASP.NET Core Web API Project Locally + +Create a new ASP.NET Core Web API project in Visual Studio 2022 targeting .NET 6.0 or later: + +```bash +dotnet new webapi -n PdfGenerationApp +cd PdfGenerationApp +``` + +### Step 2: Install Syncfusion.Pdf.NET NuGet Package + +```bash +dotnet add package Syncfusion.Pdf.NET +``` + +Or use the NuGet Package Manager in Visual Studio to add the latest version of `Syncfusion.Pdf.NET`. + +### Step 3: Register License Key in Program.cs + +Add your Syncfusion license key registration at application startup: + +{% tabs %} +{% highlight c# tabtitle="Program.cs" %} + +using Syncfusion.Licensing; + +// Register license before building services +SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + +var builder = WebApplicationBuilder.CreateBuilder(args); + +builder.Services.AddControllers(); +builder.Services.AddCors(options => +{ + options.AddPolicy("AllowAll", policy => + policy.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader()); +}); + +var app = builder.Build(); +app.UseHttpsRedirection(); +app.UseCors("AllowAll"); +app.MapControllers(); +app.Run(); + +{% endhighlight %} +{% endtabs %} + +### Step 4: Create PDF Controller + +Create a new controller file `PdfController.cs` with the following implementation: + +{% tabs %} +{% highlight c# tabtitle="PdfController.cs" %} + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Microsoft.AspNetCore.Mvc; +using Syncfusion.Drawing; +using Syncfusion.Pdf; +using Syncfusion.Pdf.Graphics; +using Syncfusion.Pdf.Grid; + +namespace PdfGenerationApp.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class PdfController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + /// + /// Generate and return a PDF document with sample data + /// + [HttpGet("generate")] + [Produces("application/pdf")] + public IActionResult GeneratePdf() + { + try + { + using (MemoryStream stream = CreateSamplePdf()) + { + return File(stream.ToArray(), "application/pdf", "Sample.pdf"); + } + } + catch (Exception ex) + { + return StatusCode(500, new { error = $"PDF generation failed: {ex.Message}" }); + } + } + + private MemoryStream CreateSamplePdf() + { + // Generate sample data + var data = Enumerable.Range(1, 5).Select(i => new + { + Date = DateTime.Now.AddDays(i), + Value = new Random().Next(1, 100), + Summary = Summaries[new Random().Next(Summaries.Length)] + }).ToList(); + + // Create PDF document + using (PdfDocument document = new PdfDocument()) + { + PdfPage page = document.Pages.Add(); + + // Add title + PdfStandardFont titleFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20, PdfFontStyle.Bold); + PdfTextElement title = new PdfTextElement("Sample PDF Report", titleFont); + title.Draw(page, new PointF(10, 10)); + + // Create data grid + PdfGrid grid = new PdfGrid(); + grid.DataSource = data; + grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.TableStyleMedium2); + + // Draw grid on page + grid.Draw(page, new PointF(10, 50)); + + // Save to stream + MemoryStream stream = new MemoryStream(); + document.Save(stream); + stream.Position = 0; + return stream; + } + } + } +} + +{% endhighlight %} +{% endtabs %} + +### Step 5: Publish to Azure App Service + +**Option A: Using Visual Studio** + +1. Right-click the project → Select **Publish** +2. Choose **Azure** as the target +3. Select **Azure App Service (Windows)** or **Azure App Service (Linux)** +4. Create a new App Service or select existing +5. Configure settings and publish + +**Option B: Using Azure CLI** + +```bash +# Login to Azure +az login + +# Create resource group +az group create --name myResourceGroup --location eastus + +# Create App Service plan +az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku B1 + +# Create web app +az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name myPdfApp + +# Deploy application +dotnet publish -c Release +cd bin/Release/net6.0/publish +az webapp deployment source config-zip --resource-group myResourceGroup --name myPdfApp --src-path app.zip +``` + +### Step 6: Test the Deployed Application + +Navigate to `https://.azurewebsites.net/swagger/index.html` and test the `/api/pdf/generate` endpoint. + +--- + +## Creating PDF Documents in Azure Functions + +Azure Functions provide a serverless approach to PDF generation, ideal for event-triggered scenarios. + +### Step 1: Create Azure Functions Project + +```bash +func new --template "HTTP trigger" --name GeneratePdf +``` + +### Step 2: Install Dependencies + +Add the Syncfusion.Pdf.NET package to your function project: + +```bash +dotnet add package Syncfusion.Pdf.NET +``` + +### Step 3: Implement PDF Generation Function + +Update the function code to generate PDFs: + +{% tabs %} +{% highlight c# tabtitle="GeneratePdf.cs" %} + +using System; +using Microsoft.Azure.Functions.Worker; +using Microsoft.Azure.Functions.Worker.Http; +using Microsoft.Extensions.Logging; +using Syncfusion.Licensing; +using Syncfusion.Pdf; +using System.IO; + +namespace Company.Functions +{ + public static class GeneratePdf + { + [Function("GeneratePdf")] + public static HttpResponseData Run( + [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] + HttpRequestData req, + FunctionContext executionContext) + { + var logger = executionContext.GetLogger("GeneratePdf"); + + try + { + // Register license + SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + + // Create PDF document + using (PdfDocument document = new PdfDocument()) + { + PdfPage page = document.Pages.Add(); + + using (PdfStandardFont font = new PdfStandardFont(Syncfusion.Pdf.PdfFontFamily.Helvetica, 20)) + { + page.Graphics.DrawString("Azure Function Generated PDF", font, + Syncfusion.Drawing.PdfBrushes.Black, new Syncfusion.Drawing.PointF(10, 10)); + } + + // Save to memory stream + MemoryStream stream = new MemoryStream(); + document.Save(stream); + stream.Position = 0; + + // Return PDF response + var response = req.CreateResponse(System.Net.HttpStatusCode.OK); + response.Headers.Add("Content-Type", "application/pdf"); + response.Headers.Add("Content-Disposition", "attachment; filename=Report.pdf"); + response.Body = stream; + return response; + } + } + catch (Exception ex) + { + logger.LogError($"Error generating PDF: {ex.Message}"); + var response = req.CreateResponse(System.Net.HttpStatusCode.InternalServerError); + response.WriteAsJsonAsync(new { error = ex.Message }); + return response; + } + } + } +} + +{% endhighlight %} +{% endtabs %} + +### Step 4: Deploy Azure Function + +```bash +func azure functionapp publish +``` + +### Step 5: Test the Function + +```bash +curl https://.azurewebsites.net/api/GeneratePdf -v +``` + +--- + +## Creating PDF Documents in Azure Kubernetes Service (AKS) + +For enterprise-scale deployments, AKS provides Kubernetes orchestration with full control. + +### Step 1: Create Docker Container Image + +Create a `Dockerfile` for your PDF generation application: + +```dockerfile +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +WORKDIR /src +COPY ["PdfGenerationApp.csproj", "./"] +RUN dotnet restore "PdfGenerationApp.csproj" +COPY . . +RUN dotnet build "PdfGenerationApp.csproj" -c Release -o /app/build + +FROM mcr.microsoft.com/dotnet/aspnet:8.0 +WORKDIR /app +COPY --from=build /app/build . +ENTRYPOINT ["dotnet", "PdfGenerationApp.dll"] +EXPOSE 80 443 +``` + +### Step 2: Build and Push to Azure Container Registry + +```bash +# Login to Azure Container Registry +az acr login --name + +# Build image +az acr build --registry --image pdf-app:latest . + +# Get image URI +az acr repository show --name --repository pdf-app --query "loginServer" +``` + +### Step 3: Deploy to AKS + +Create a Kubernetes deployment manifest `pdf-deployment.yaml`: + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: pdf-generator +spec: + replicas: 3 + selector: + matchLabels: + app: pdf-generator + template: + metadata: + labels: + app: pdf-generator + spec: + containers: + - name: pdf-app + image: .azurecr.io/pdf-app:latest + ports: + - containerPort: 80 + env: + - name: SYNCFUSION_LICENSE + valueFrom: + secretKeyRef: + name: syncfusion-secret + key: license-key + resources: + requests: + memory: "256Mi" + cpu: "250m" + limits: + memory: "512Mi" + cpu: "500m" +--- +apiVersion: v1 +kind: Service +metadata: + name: pdf-service +spec: + type: LoadBalancer + selector: + app: pdf-generator + ports: + - protocol: TCP + port: 80 + targetPort: 80 +``` + +Deploy to AKS: + +```bash +# Create secret for license +kubectl create secret generic syncfusion-secret --from-literal=license-key='YOUR_LICENSE_KEY' + +# Deploy application +kubectl apply -f pdf-deployment.yaml + +# Verify deployment +kubectl get pods +kubectl get svc +``` + +--- + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| **License Key Not Registered** | Ensure `SyncfusionLicenseProvider.RegisterLicense()` is called before any PDF operations. For Azure Functions and AKS, use environment variables or Azure Key Vault to securely store license keys. Verify the license key is active and not expired in the Syncfusion portal. | +| **Syncfusion.Pdf.NET Package Not Found** | Install the latest version from NuGet: `dotnet add package Syncfusion.Pdf.NET`. Verify your .csproj targets .NET 6.0 or later. If using older .NET Framework, use `Syncfusion.Pdf.WinForms` instead. | +| **"Cannot connect to Blob Storage"** | Configure connection strings in Azure Key Vault or appsettings.json. For managed identity authentication, enable System Assigned Identity on the App Service/Function and grant Storage Blob Data Contributor role. | +| **PDF Generation Timeout in Azure Functions** | Default timeout is 5 minutes. For large PDFs, increase function timeout in `host.json`: `"functionTimeout": "00:10:00"`. Consider using Durable Functions for very large operations. Use streaming instead of buffering entire document. | +| **Memory Issues with Large Reports** | Stream PDFs directly instead of buffering. Use `PdfDocument` with streaming: `document.Save(stream)` instead of loading entire document into memory. For AKS, increase pod memory limits in deployment manifest. | +| **Docker Image Build Fails** | Ensure base image matches architecture (amd64 for most Azure services). Verify all NuGet packages are available during build. Use multi-stage builds to reduce final image size. Check Docker build output for specific errors. | +| **CORS Errors in Web App** | Add CORS policy in Program.cs: `builder.Services.AddCors()` and `app.UseCors()`. For Azure Functions, use Azure API Management or a middleware solution. Verify Origin header matches allowed domains. | +| **"404 Not Found" on Azure App Service** | Verify controller route matches your request URL (routes are case-sensitive). Ensure `app.MapControllers()` is called in Program.cs. Check application settings: navigate to Azure portal → your app → Configuration. | +| **PDF File Permission Denied (Linux)** | Ensure file paths use forward slashes `/` and the running identity has write permissions. For App Service on Linux, write to `/tmp` or `/home`. For AKS, mount PersistentVolume if persistent storage needed. | +| **Deployment Fails with "Invalid Credentials"** | Verify Azure login: `az login`. Check Azure subscription quota limits. Ensure resource group exists. For AKS, verify cluster credentials: `az aks get-credentials --resource-group --name `. | +| **"Out of Memory" in AKS Pods** | Check actual memory usage: `kubectl top pods`. Increase pod limits in deployment yaml. Implement memory-efficient PDF creation: use streaming, avoid loading entire document into memory, clean up resources with `using` statements. | + +## Next Steps + +Explore advanced PDF capabilities for Azure deployments: + +### Advanced PDF Features +- **[Merge Multiple PDFs](https://help.syncfusion.com/file-formats/pdf/working-with-documents/merge-documents)** — Combine reports and documents on-demand in cloud +- **[Split PDF Documents](https://help.syncfusion.com/file-formats/pdf/split-document)** — Extract specific pages or create page ranges in serverless functions +- **[Add Watermarks & Stamps](https://help.syncfusion.com/file-formats/pdf/working-with-pages/add-watermark)** — Brand PDFs with company logos and confidentiality markers +- **[Create Interactive Forms](https://help.syncfusion.com/file-formats/pdf/working-with-forms/overview)** — Build fillable PDF forms for data collection +- **[Digital Signatures](https://help.syncfusion.com/file-formats/pdf/working-with-forms/create-digital-signatures)** — Sign PDFs programmatically for compliance and authenticity +- **[PDF Encryption & Security](https://help.syncfusion.com/file-formats/pdf/working-with-forms/encryption)** — Protect sensitive documents with passwords and permissions +- **[Advanced Formatting](https://help.syncfusion.com/file-formats/pdf/working-with-tables)** — Generate complex tables, charts, and multi-column layouts + +### Azure Integration Patterns +- **[Store PDFs in Azure Blob Storage](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction)** — Use managed identity for secure, scalable storage +- **[Azure Storage Queue Triggers](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue)** — Trigger PDF generation from storage events +- **[Azure Event Grid Integration](https://learn.microsoft.com/en-us/azure/event-grid/overview)** — Event-driven PDF workflows across Azure services +- **[Azure Service Bus Messaging](https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messaging-overview)** — Reliable PDF generation queue with retry logic +- **[Cosmos DB Integration](https://learn.microsoft.com/en-us/azure/cosmos-db/introduction)** — Query data and generate PDFs from globally distributed data +- **[Azure API Management](https://learn.microsoft.com/en-us/azure/api-management/api-management-key-concepts)** — Secure, throttle, and monitor PDF generation APIs + +### Deployment & Operations +- **[Azure Monitor & Application Insights](https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview)** — Track PDF generation performance and errors +- **[Azure Key Vault](https://learn.microsoft.com/en-us/azure/key-vault/general/overview)** — Securely manage Syncfusion license keys and secrets +- **[Auto-scaling Policies](https://learn.microsoft.com/en-us/azure/app-service/manage-scale-up)** — Scale App Service and Functions based on PDF demand +- **[Continuous Integration/Deployment (CI/CD)](https://learn.microsoft.com/en-us/azure/devops/pipelines/overview)** — Automate PDF app deployment with Azure Pipelines +- **[Disaster Recovery Planning](https://learn.microsoft.com/en-us/azure/architecture/resiliency/)** — Implement failover and backup strategies + +--- + +## Resources + +**Sample Projects:** +- [Syncfusion PDF Examples on GitHub](https://github.com/SyncfusionExamples/PDF-Examples) +- [Azure App Service Samples](https://github.com/Azure-Samples/app-service-samples) +- [Azure Functions Samples](https://github.com/Azure-Samples/azure-functions-samples) + +**Documentation:** +- [Syncfusion .NET PDF Library Documentation](https://help.syncfusion.com/file-formats/pdf/) +- [Microsoft Azure Documentation](https://learn.microsoft.com/en-us/azure/) +- [.NET Documentation](https://learn.microsoft.com/en-us/dotnet/) + +**Try It Out:** +- [Syncfusion PDF Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) +- [Azure Free Account](https://azure.microsoft.com/en-us/free/) +- [Azure Functions Free Tier](https://azure.microsoft.com/en-us/services/functions/) + + diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-AKS-Environment.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-AKS-Environment.md index 148a756ee1..7fcce0213b 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-AKS-Environment.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-AKS-Environment.md @@ -1,14 +1,30 @@ --- -title: Create PDF document in AKS Environment | Syncfusion -description: Create PDF document in AKS Environment using .NET PDF library without the dependency of Adobe Acrobat. +title: Create a PDF File in Azure Kubernetes Service (AKS) | Syncfusion +description: Learn how to create a PDF file in Azure Kubernetes Service (AKS) using .NET PDF library without the dependency of Adobe Acrobat. platform: file-formats control: PDF documentation: UG --- -# Create PDF document in AKS Environment +# Create a PDF File in Azure Kubernetes Service (AKS) -The [.NET Core PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, edit PDF documents programmatically without the dependency of Adobe Acrobat. Using this library, you can **create PDF document in AKS Environment**. +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents programmatically without the dependency of Adobe Acrobat. This guide shows how to containerize an ASP.NET Core app that generates PDFs and deploy it to Azure Kubernetes Service (AKS). + +## Prerequisites + +| Requirement | Version | +|---|---| +| **Visual Studio** | 2022 or later (with Docker support) | +| **.NET Framework** | .NET 6.0 or later | +| **Docker Desktop** | Latest version with Kubernetes enabled | +| **Azure CLI** | Latest version | +| **kubectl** | Latest version (usually comes with Docker Desktop) | +| **Azure Subscription** | Required for AKS cluster and container registry | +| **NuGet Package** | Syncfusion.Pdf.NET (latest stable version) | + +**Azure Resources Required:** +- Azure Container Registry (ACR) — for storing container images +- Azure Kubernetes Service (AKS) cluster — for deploying containerized app ## Steps to create PDF document in AKS Environment @@ -21,11 +37,30 @@ Step 2: Create a project name and select the location. Step 3: Click **Create** button. ![Additional Information](AKS_images/Sample_addition_information.png) -Step 4: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core/) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). +Step 4: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.NET/) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). ![Install Syncfusion.Pdf.Net.Core NuGet package](AKS_images/NuGet_package.png) +Step 5: Register the Syncfusion license in **Program.cs** (for .NET 6+) or **Startup.cs** (.NET Core 3.1): + +{% tabs %} +{% highlight c# tabtitle="Program.cs (.NET 6+)" %} + +using Syncfusion.Licensing; + +var builder = WebApplication.CreateBuilder(args); + +// Register Syncfusion license +SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + +builder.Services.AddControllersWithViews(); +var app = builder.Build(); + +{% endhighlight %} +{% endtabs %} + +Replace `YOUR_LICENSE_KEY` with your actual Syncfusion license key. -Step 5: A default action method named Index will be present in *HomeController.cs*. Right click on Index method and select Go To View where you will be directed to its associated view page *Index.cshtml*. Add a new button in the *Index.cshtml* as shown below. +Step 6: A default action method named Index will be present in *HomeController.cs*. Right click on Index method and select Go To View where you will be directed to its associated view page *Index.cshtml*. Add a new button in the *Index.cshtml* as shown below. {% tabs %} {% highlight CSHTML %} @@ -43,90 +78,126 @@ Step 5: A default action method named Index will be present in *HomeController.c {% endhighlight %} {% endtabs %} -Step 6: Include the following namespaces in *HomeController.cs*. +Step 7: Include the following namespaces in *HomeController.cs*. {% tabs %} {% highlight c# tabtitle="C#" %} -using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf; -using System.Diagnostics; +using Syncfusion.Pdf.Graphics; using Syncfusion.Drawing; {% endhighlight %} {% endtabs %} -Step 7: Add a new action method named CreatePDFDocument in HomeController.cs file and include the below code example to generate a PDF document in *HomeController.cs*. +Step 8: Add a new action method named CreatePDFDocument in HomeController.cs file. First, inject **IWebHostEnvironment** in the constructor, then add the action method as shown below: {% tabs %} {% highlight c# tabtitle="C#" %} +private readonly IWebHostEnvironment _hostingEnvironment; + +public HomeController(IWebHostEnvironment hostingEnvironment) +{ + _hostingEnvironment = hostingEnvironment; +} + public IActionResult CreatePDFDocument() { - //Create a new PDF document. - PdfDocument document = new PdfDocument(); - //Set the page size. - document.PageSettings.Size = PdfPageSize.A4; - //Add a page to the document. - PdfPage page = document.Pages.Add(); - - //Create PDF graphics for the page. - PdfGraphics graphics = page.Graphics; - //Load the image from the disk. - string imagePath = Path.Combine(_hostingEnvironment.WebRootPath, "Data/AdventureCycle.jpg"); - FileStream imageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read); - PdfBitmap image = new PdfBitmap(imageStream); - //Draw an image. - graphics.DrawImage(image, new RectangleF(130, 0, 250, 100)); - - //Draw header text. - graphics.DrawString("Adventure Works Cycles", new PdfStandardFont(PdfFontFamily.TimesRoman, 20, PdfFontStyle.Bold), PdfBrushes.Gray, new PointF(150, 150)); - - //Add paragraph. - string text = "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Washington with 290 employees, several regional sales teams are located throughout their market base."; - //Create a text element with the text and font. - PdfTextElement textElement = new PdfTextElement(text, new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); - //Draw the text in the first column. - textElement.Draw(page, new RectangleF(0, 200, page.GetClientSize().Width, page.GetClientSize().Height)); - - //Create a PdfGrid. - PdfGrid pdfGrid = new PdfGrid(); - //Add values to the list. - List data = new List(); - Object row1 = new { Product_ID = "1001", Product_Name = "Bicycle", Price = "10,000" }; - Object row2 = new { Product_ID = "1002", Product_Name = "Head Light", Price = "3,000" }; - Object row3 = new { Product_ID = "1003", Product_Name = "Break wire", Price = "1,500" }; - data.Add(row1); - data.Add(row2); - data.Add(row3); - //Add list to IEnumerable. - IEnumerable dataTable = data; - //Assign data source. - pdfGrid.DataSource = dataTable; - //Apply built-in table style. - pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); - //Draw the grid to the page of PDF document. - pdfGrid.Draw(graphics, new RectangleF(0, 300, page.Size.Width - 80, 0)); - - //Saving the PDF to the MemoryStream. - MemoryStream stream = new MemoryStream(); - document.Save(stream); - //Set the position as '0'. - stream.Position = 0; - //Download the PDF document in the browser. - FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); - fileStreamResult.FileDownloadName = "Sample.pdf"; - return fileStreamResult; + try + { + //Create a new PDF document. + using (PdfDocument document = new PdfDocument()) + { + //Set the page size. + document.PageSettings.Size = PdfPageSize.A4; + //Add a page to the document. + PdfPage page = document.Pages.Add(); + + //Create PDF graphics for the page. + PdfGraphics graphics = page.Graphics; + + //Load the image from the disk. + string imagePath = Path.Combine(_hostingEnvironment.WebRootPath, "Data/AdventureCycle.jpg"); + using (FileStream imageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) + { + PdfBitmap image = new PdfBitmap(imageStream); + //Draw an image. + graphics.DrawImage(image, new RectangleF(130, 0, 250, 100)); + } + + //Draw header text. + graphics.DrawString("Adventure Works Cycles", new PdfStandardFont(PdfFontFamily.TimesRoman, 20, PdfFontStyle.Bold), PdfBrushes.Gray, new PointF(150, 150)); + + //Add paragraph. + string text = "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Washington with 290 employees, several regional sales teams are located throughout their market base."; + //Create a text element with the text and font. + PdfTextElement textElement = new PdfTextElement(text, new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); + //Draw the text in the first column. + textElement.Draw(page, new RectangleF(0, 200, page.GetClientSize().Width, page.GetClientSize().Height)); + + //Create a PdfGrid. + PdfGrid pdfGrid = new PdfGrid(); + //Add values to the list. + List data = new List(); + Object row1 = new { Product_ID = "1001", Product_Name = "Bicycle", Price = "10,000" }; + Object row2 = new { Product_ID = "1002", Product_Name = "Head Light", Price = "3,000" }; + Object row3 = new { Product_ID = "1003", Product_Name = "Break wire", Price = "1,500" }; + data.Add(row1); + data.Add(row2); + data.Add(row3); + //Add list to IEnumerable. + IEnumerable dataTable = data; + //Assign data source. + pdfGrid.DataSource = dataTable; + //Apply built-in table style. + pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); + //Draw the grid to the page of PDF document. + pdfGrid.Draw(graphics, new RectangleF(0, 300, page.Size.Width - 80, 0)); + + //Saving the PDF to the MemoryStream. + using (MemoryStream stream = new MemoryStream()) + { + document.Save(stream); + //Set the position as '0'. + stream.Position = 0; + //Download the PDF document in the browser. + byte[] bytes = stream.ToArray(); + return File(bytes, "application/pdf", "Sample.pdf"); + } + } + } + catch (Exception ex) + { + return BadRequest($"Error generating PDF: {ex.Message}"); + } } {% endhighlight %} {% endtabs %} -**Publish Container to ACR** +## Containerize the Application + +Step 9: Before publishing to Azure Container Registry, ensure your project includes a **Dockerfile**. If not present, Visual Studio 2022 can generate one automatically: + +1. Right-click the project → **Add** → **Docker Support** +2. Select **Linux** as the target OS and click **Create Dockerfile** +3. The generated Dockerfile will configure the .NET runtime and application entry point + +Alternatively, create a `Dockerfile` manually in the project root: + +```dockerfile +FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS runtime +WORKDIR /app +COPY --from=builder /app/publish . +ENTRYPOINT ["dotnet", "YourAppName.dll"] +``` + +## Publish Container to ACR Step 1: Right-click the project and select Publish option. ![Right-click the project and select the Publish option](AKS_images/Click_publish_button.png) @@ -149,15 +220,15 @@ Step 6: Click **Close** button. Step 7: Click the **Publish** button. ![Click the Publish button](AKS_images/Publish_app_service.png) -Step 8: It will push the docker image to the Azure container registry and deploy it to the Azure container instance. -![Push the docker image to the Azure container](AKS_images/Push_the_docker_image.png) +Step 8: It will push the Docker image to the Azure Container Registry. +![Push the Docker image to the Azure Container Registry](AKS_images/Push_the_docker_image.png) Step 9: Publish succeeded. ![Publish succeeded](AKS_images/Publish_link.png) -**Deploy Container Image to AKS** +## Deploy Container Image to AKS -Step 1: Now we can deploy container to the AKS cluster. Start by opening the Azure portal, browsing to the Subscription and opening the Cloud Shell (BASH). We will use the kubectl tool to manage the cluster. +Step 1: Now you can deploy the container to the AKS cluster. Start by opening the Azure portal, navigating to your Subscription, and opening the Cloud Shell (BASH). You will use the kubectl tool to manage the cluster. Step 2: You need to gather the credentials in order to interact with the cluster using kubectl in Azure Cloud Shell. use the following command: @@ -193,39 +264,45 @@ code deploy.yaml {% endtabs %} -Step 5: Then we pasted in the following Kubernetes Deployment and Service configurations. Note, change yours to match your app name, container name, registry, etc. +Step 5: Add the following Kubernetes Deployment and Service configurations. **Important:** Customize the values below to match your specific setup: + - Replace `createpdfdocument` with your application name + - Replace `createpdfdocument20240918103106.azurecr.io` with your ACR login server (from Azure portal) + - Update the image tag to match your published image + {% tabs %} {% highlight bash %} apiVersion: apps/v1 kind: Deployment metadata: -name: createpdfdocument + name: createpdfdocument spec: -replicas: 2 -selector: + replicas: 2 # Number of pod instances (increase for higher load) + selector: matchLabels: - app: createpdfdocument -template: + app: createpdfdocument + template: metadata: - labels: + labels: app: createpdfdocument spec: - containers: - - name: createpdfdocument + containers: + - name: createpdfdocument image: createpdfdocument20240918103106.azurecr.io/createpdfdocument:latest + ports: + - containerPort: 80 --- apiVersion: v1 kind: Service metadata: -name: createpdfdocument + name: createpdfdocument spec: -type: LoadBalancer -ports: + type: LoadBalancer + ports: - port: 80 - targetPort: 80 - protocol: TCP -selector: + targetPort: 80 + protocol: TCP + selector: app: createpdfdocument {% endhighlight %} @@ -242,23 +319,18 @@ kubectl apply -f deploy.yaml {% endtabs %} -Step 7: Notice the deployment and service shows as created. +Step 7: Notice the deployment and service are created. -![Deployemnt created](AKS_images/Deployemnt_created.png) +![Deployment created](AKS_images/Deployment_created.png) -Step 8: You can run the following commands: -{% tabs %} -{% highlight bash %} - -kubectl get pods -kubectl get nodes -kubectl get service -kubectl describe deployment +Step 8: You can run the following commands to verify the deployment: -{% endhighlight %} -{% endtabs %} +- `kubectl get pods` — Lists all running container instances (pods) +- `kubectl get nodes` — Lists the cluster nodes (virtual machines) +- `kubectl get service` — Lists all services, including the LoadBalancer IP and port +- `kubectl describe deployment` — Shows detailed deployment information -or +Alternatively, run: {% tabs %} {% highlight bash %} @@ -267,7 +339,9 @@ kubectl get all {% endhighlight %} {% endtabs %} -Step 9: This will show the pods, services, apps and replica sets. +This displays all pods, services, apps, and replica sets. + +Step 9: The output shows the pods, services, apps, and replica sets: ![Kubectl details](AKS_images/Kubectl_details.png). Step 10: We can see the EXTERNAL-IP of the LoadBalancer above as being 20.117.254.138 and the port as 80. I should now be able to use this to browse the the web app running on AKS. @@ -276,12 +350,25 @@ Step 10: We can see the EXTERNAL-IP of the LoadBalancer above as being 20.117.25 If we head over to the Azure portal, select the AKS resource > Workloads > asp-docker-app, we can see the pods. ![Pods details](AKS_images/Pods_details.png). -And that’s it, the containerised ASP.NET Core Web App is running on the AKS cluster. +And that's it, the containerized ASP.NET Core Web App is running on the AKS cluster. + +In your browser, navigate to the external IP address (from Step 10) and click **Create PDF Document** button to generate the PDF. You will see the output PDF document as follows: +![Create PDF document in AKS](AKS_images/Output.png) + +## Troubleshooting -Select the PDF document and Click **Create PDF document** to generate the PDF document.You will get the output **PDF document** as follows. -![Create PDF document in Azure App Service on Linux](AKS_images/Output.png) +| Issue | Cause | Solution | +|---|---|---| +| **Image pull errors** | ACR not attached to AKS or credentials missing | Run: `az aks update -n cluster-name -g resource-group --attach-acr registry-name` | +| **Pod crashes with CrashLoopBackOff** | Missing dependencies or license registration failed | Check logs: `kubectl logs ` and verify license registration in Program.cs | +| **External IP shows \** | LoadBalancer service not provisioned | Wait 2-3 minutes, then retry `kubectl get service` | +| **Cannot reach application** | Firewall or network security group blocking port 80 | Check Azure NSG rules allow inbound traffic on port 80 | +| **Deployment fails to pull image** | Wrong registry URL or image tag in deploy.yaml | Verify registry name and image tag match ACR login server | +| **Out of memory/CPU errors** | Resource limits too restrictive or too many replicas | Add resource requests/limits to deployment.yaml and scale replicas | +| **kubectl commands fail** | Credentials not configured for cluster | Re-run: `az aks get-credentials --resource-group rg-name --name cluster-name` | +| **PDF file is blank** | Image path not found or graphics operations failed | Verify `Data/AdventureCycle.jpg` exists in wwwroot folder; check application logs | -**Delete deployment** +## Clean Up: Delete Deployment and Service If you want to clean up the cluster, you can run the following commands: {% tabs %} @@ -297,4 +384,13 @@ You can download a complete working sample from [GitHub](https://github.com/Sync Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). + +## Next Steps + +- **[Scale AKS deployments](https://learn.microsoft.com/en-us/azure/aks/scale-cluster)** — Increase replicas and node pools for higher load +- **[Monitor AKS with Azure Monitor](https://learn.microsoft.com/en-us/azure/aks/monitor-aks)** — Track performance, logs, and diagnostics +- **[Set up continuous deployment (CI/CD)](https://learn.microsoft.com/en-us/azure/aks/devops-pipeline)** — Automate builds and deployments with Azure Pipelines +- **[Merge PDF files](https://help.syncfusion.com/document-processing/pdf-library/net/merge-pdf-files)** — Combine multiple PDFs in your containerized app +- **[Secure PDF documents](https://help.syncfusion.com/document-processing/pdf-library/net/securing-pdf-documents)** — Add encryption and permissions to generated PDFs +- **[Deploy to other Azure services](https://help.syncfusion.com/document-processing/pdf-library/net)** — Create PDFs in App Service, Functions, or other platforms \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-App-Service-Linux.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-App-Service-Linux.md index 4ce6781c41..4e46bf72da 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-App-Service-Linux.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-App-Service-Linux.md @@ -1,6 +1,6 @@ --- title: Create PDF document in Azure App Service on Linux | Syncfusion -description: Create PDF document in Azure App Service on Linux using .NET PDF library without the dependency of Adobe Acrobat. +description: Create a PDF document in Azure App Service on Linux using the Syncfusion .NET PDF library without the dependency on Adobe Acrobat. platform: document-processing control: PDF documentation: UG @@ -8,25 +8,42 @@ documentation: UG # Create PDF document in Azure App Service on Linux -The [.NET Core PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, edit PDF documents programmatically without the dependency of Adobe Acrobat. Using this library, you can **create PDF document in Azure App Service on Linux**. +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, edit PDF documents programmatically without the dependency on Adobe Acrobat. Using this library, you can **create a PDF document in Azure App Service on Linux**. + +## Prerequisites + +| Item | Details | +| --- | --- | +| **Development Environment** | Visual Studio 2022 or Visual Studio Code with C# extension | +| **.NET Version** | .NET 8.0 or later | +| **NuGet Package** | Syncfusion.Pdf.NET (latest version) | +| **Azure Subscription** | Active Microsoft Azure account with resource group | +| **Azure CLI** | Optional but recommended for deployment | +| **License** | Syncfusion license key (required for production deployments) | +| **Image Assets** | Place sample images in `wwwroot/images/` folder | ## Steps to create PDF document in Azure App Service on Linux -Step 1: Create a new ASP.NET Core Web App (Model-View-Controller). -![Create a ASP.NET Core Web App project](Azure_images/Azure-app-service-Linux/Create-net-core-web-app.png) +Step 1: Create a new ASP.NET Core Web App (Model-View-Controller) in Visual Studio. +![Create an ASP.NET Core Web App project](Azure_images/Azure-app-service-Linux/Create-net-core-web-app.png) -Step 2: Create a project name and select the location. +Step 2: Set the project name and select the location. ![Configure your new project](Azure_images/Azure-app-service-Linux/Set_project_name.png) -Step 3: Click **Create** button. +Step 3: Click the **Create** button. ![Additional Information](Azure_images/Azure-app-service-Linux/Sample_addition_information.png) -Step 4: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core/) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). +Step 4: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core/) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). You can also use the .NET CLI: + +```bash +dotnet add package Syncfusion.Pdf.Net.Core +``` + ![Install Syncfusion.Pdf.Net.Core NuGet package](Azure_images/Azure-app-service-Linux/NuGet_package.png) -N> Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, you also have to add "Syncfusion.Licensing" assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to know about registering Syncfusion license key in your application to use our components. +N> Starting with v16.2.0.x, if you reference Syncfusion assemblies from a trial setup or from the NuGet feed, you must also add the **Syncfusion.Licensing** assembly reference and include a license key in your project. Refer to the [licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for details. -Step 5: A default action method named Index will be present in *HomeController.cs*. Right click on Index method and select Go To View where you will be directed to its associated view page *Index.cshtml*. Add a new button in the *Index.cshtml* as shown below. +Step 5: A default action method named `Index` is present in *HomeController.cs*. Right-click the `Index` method and select **Go To View** to open its associated view page *Index.cshtml*. Add a new button to *Index.cshtml* as shown below. {% tabs %} @@ -46,12 +63,15 @@ Step 5: A default action method named Index will be present in *HomeController.c {% endtabs %} -Step 6: Include the following namespaces in *HomeController.cs*. +Step 6: Include the following namespaces in *HomeController.cs*. Add `System.IO` and `System.Collections.Generic` for the `FileStream`, `Path`, and `List` types used in the action method. {% tabs %} {% highlight c# tabtitle="C#" %} +using System.IO; +using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; using Syncfusion.Pdf.Graphics; using Syncfusion.Drawing; using Syncfusion.Pdf.Grid; @@ -61,7 +81,7 @@ using Syncfusion.Pdf; {% endtabs %} -Step 7: Add a new action method named CreatePDFDocument in HomeController.cs file and include the below code example to generate a PDF document in *HomeController.cs*. +Step 7: Add a new action method named `CreatePDFDocument` in the *HomeController.cs* file and include the following code to generate a PDF document. Before building, place the sample image at `wwwroot/Data/AdventureCycle.jpg` so the controller can read it at runtime. {% tabs %} @@ -136,49 +156,90 @@ public IActionResult CreatePDFDocument() {% endtabs %} -**Steps to publish as Azure App Service on Linux** +**Verify locally before publishing** -Step 1: Right-click the project and select Publish option. +Run the project locally with `F5` in Visual Studio, then click the **Create PDF Document** button on the home page to confirm the PDF downloads successfully. If you see a license warning, ensure `Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY")` is called at application startup (for example, in `Program.cs`). + +## Steps to publish as Azure App Service on Linux + +Step 1: Right-click the project and select **Publish**. ![Right-click the project and select the Publish option](Azure_images/Azure-app-service-Linux/Click_publish_button.png) -Step 2: Click the **Add a Publish Profile** button. +Step 2: Click the **Add a Publish Profile** button. Sign in to your Azure account if prompted. ![Click the Add a Publish Profile](Azure_images/Azure-app-service-Linux/Add_publish_profile.png) Step 3: Select the publish target as **Azure**. ![Select the publish target as Azure](Azure_images/Azure-app-service-Linux/Publish_target.png) -Step 4: Select the Specific target as **Azure App Service (Linux)**. +Step 4: Select the specific target as **Azure App Service (Linux)**. ![Select the publish target](Azure_images/Azure-app-service-Linux/Specific_target.png) -Step 5: To create a new app service, click **Create new** option. +Step 5: To create a new app service, click the **Create new** option. ![Click create new option](Azure_images/Azure-app-service-Linux/Create_new_app_service.png) -Step 6: Click the **Create** button to proceed with **App Service** creation. +Step 6: Configure the **App Service name**, **Subscription**, **Resource Group**, and **App Service Plan**, then click the **Create** button to proceed with the App Service creation. ![Click the Create button](Azure_images/Azure-app-service-Linux/Host_plan.png) Step 7: Click the **Finish** button to finalize the **App Service** creation. ![Click the Finish button](Azure_images/Azure-app-service-Linux/App_service_finish.png) -Step 8: Click deployment type. +Step 8: Select the deployment type. ![Create a Deployment type](Azure_images/Azure-app-service-Linux/Deployment_type.png) -Step 9: Click **Close** button. -![Create a ASP.NET Core Project](Azure_images/Azure-app-service-Linux/Publish_profile_creation_progress.png) +Step 9: Click the **Close** button. +![Create an ASP.NET Core Project](Azure_images/Azure-app-service-Linux/Publish_profile_creation_progress.png) Step 10: Click the **Publish** button. ![Click the Publish button](Azure_images/Azure-app-service-Linux/Ready_to_publish_window.png) -Step 11: Now, Publish has been succeeded. +Step 11: Publishing has succeeded. ![Publish has been succeeded](Azure_images/Azure-app-service-Linux/Successful_publish.png) -Step 12: Now, the published webpage will open in the **browser**. +Step 12: The published webpage will open in the **browser**. ![Browser will open after publish](Azure_images/Azure-app-service-Linux/WebView.png) -Step 13: Select the PDF document and Click **Create PDF document** to generate the PDF document.You will get the output **PDF document** as follows. +Step 13: Click the **Create PDF document** button to generate the PDF document. The output PDF document appears as follows. ![Create PDF document in Azure App Service on Linux](Azure_images/Azure-app-service-Linux/Output.png) You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Azure/Azure%20App%20Service). -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. - -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion PDF library features. + +An online sample to [create a PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind) is also available. + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| **Image File Not Found** | Verify the image file exists at `wwwroot/images/AdventureCycle.jpg`. Check file permissions and case sensitivity on Linux (paths are case-sensitive). | +| **Syncfusion.Pdf.NET Package Not Found** | Run `dotnet add package Syncfusion.Pdf.NET` or use NuGet Package Manager to install the latest version targeting .NET 6.0+. | +| **"Could not find wwwroot folder"** | Verify the project structure includes a `wwwroot` folder. If missing, create it at the project root and add images to `wwwroot/images/` subdirectory. | +| **Deployment Failed with Authentication Error** | Verify you are logged into Azure: `az login`. Check Azure subscription and ensure you have permissions to create resources. | +| **Application Timeout on Startup** | If using a Free tier App Service, startup may be slow. Upgrade to B1 or higher tier for better performance. Check Application Insights logs for detailed errors. | +| **PDF Download Not Working** | Verify the controller returns `File()` with correct content type (`application/pdf`). Check browser developer tools for network errors. | +| **Missing Dependencies in Deployment** | Ensure all NuGet packages are restored during deployment. Check build output in Azure portal → Deployment Center → Logs. | +| **Memory Issues Generating Large PDFs** | Use streaming instead of buffering. For very large PDFs, consider Azure Functions with higher memory allocation instead of App Service. | + +## See also + +* [Create a PDF document in .NET](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/create-pdf-file-in-asp-net-core) +* [Azure App Service on Linux documentation](https://learn.microsoft.com/en-us/azure/app-service/overview) +* [Syncfusion.Pdf.Net.Core NuGet package](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core/) +* [Syncfusion licensing overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) + +## Next Steps + +Explore advanced PDF capabilities and Azure integration patterns: + +### Advanced PDF Features +- **[Merge Multiple PDFs](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/merge-documents)** — Combine multiple reports into a single document +- **[Split PDF Documents](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/split-documents)** — Extract specific pages or create filtered PDFs +- **[Add Watermarks](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/working-with-watermarks)** — Brand PDFs with company logos and confidentiality markers +- **[Create Interactive Forms](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/working-with-forms)** — Build fillable PDF forms for data collection +- **[Digital Signatures](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/working-with-digitalsignature)** — Sign PDFs programmatically for compliance +- +### Azure Integration Patterns +- **[Store PDFs in Azure Blob Storage](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction)** — Scalable storage for generated documents +- **[Monitor with Application Insights](https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview)** — Track PDF generation performance and errors +- **[Auto-scaling Policies](https://learn.microsoft.com/en-us/azure/app-service/manage-scale-up)** — Scale based on demand +- **[CI/CD with Azure Pipelines](https://learn.microsoft.com/en-us/azure/devops/pipelines/overview)** — Automate deployment updates diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-App-Service-Windows.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-App-Service-Windows.md index 94d046559d..57def830c9 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-App-Service-Windows.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-App-Service-Windows.md @@ -6,37 +6,109 @@ control: PDF documentation: UG --- -# Create PDF document in Azure App Service on Windows +# Create a PDF File in Azure App Service on Windows -The [.NET Core PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, edit PDF documents programmatically without the dependency of Adobe Acrobat. Using this library, you can **create PDF document in Azure App Service on Windows**. +The [Syncfusion .NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create, read, and edit PDF documents programmatically without requiring Adobe Acrobat. This guide demonstrates how to deploy an ASP.NET Core Web application that generates PDF documents to Azure App Service running on Windows. + +## Prerequisites + +| Item | Details | +| --- | --- | +| **Development Environment** | Visual Studio 2022 or Visual Studio Code with C# extension | +| **.NET Version** | .NET 6.0 or later (.NET 8.0 recommended) | +| **NuGet Package** | Syncfusion.Pdf.NET (latest version) | +| **Azure Subscription** | Active Microsoft Azure account with resource group | +| **Azure CLI** | Optional but recommended for deployment automation | +| **License** | Syncfusion license key (required for production deployments) | +| **Image Assets** | Place sample images in `wwwroot/images/` folder | + +## Video Tutorial + +For a visual walkthrough of creating and deploying a PDF generation application to Azure App Service on Windows, watch the following video: -Check the following video to learn how to create a PDF document and publish it as an Azure App Service on Windows using the .NET PDF Library. {% youtube "https://www.youtube.com/watch?v=PU8pVAHV_88" %} -## Steps to create PDF document in Azure App Service on Windows +## Steps to Create PDF Documents in Azure App Service on Windows + +**Step 1: Create a New ASP.NET Core Web App Project** + +Launch Visual Studio 2022 and create a new ASP.NET Core Web App using the Model-View-Controller (MVC) template targeting .NET 6.0 or later. -Step 1: Create a new ASP.NET Core Web App (Model-View-Controller). ![Create a ASP.NET Core Web App project](Azure_images/Azure-app-service-windows/Create-net-core-web-app.png) -Step 2: Create a project name and select the location. +**Step 2: Configure Project Settings** + +Enter your project name and select the project location. + ![Configure your new project](Azure_images/Azure-app-service-windows/project_configuration.png) -Step 3: Click **Create** button. +**Step 3: Create the Project** + +Click the **Create** button to finalize project creation and select your target framework. + ![Additional information](Azure_images/Azure-app-service-windows/Framework_selection.png) -Step 4: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core/) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). +**Step 4: Install the Syncfusion PDF Package** + +Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.NET) NuGet package from NuGet.org. Use either the NuGet Package Manager or the Package Manager Console: + +```bash +dotnet add package Syncfusion.Pdf.NET +``` + ![NuGet package installation](Azure_images/Azure-app-service-windows/NuGet_package.png) -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add "Syncfusion.Licensing" assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to know about registering Syncfusion® license key in your application to use our components. +**Step 5: Register Your Syncfusion License** -Step 5: A default action method named Index will be present in *HomeController.cs*. Right click on Index method and select Go To View where you will be directed to its associated view page *Index.cshtml*. Add a new button in the *Index.cshtml* as shown below. +Add your Syncfusion license key registration in the `Program.cs` file. Starting with v16.2.0.x, license registration is **required**. Add the following code at the application startup: + +{% tabs %} +{% highlight c# tabtitle="Program.cs" %} + +using Syncfusion.Licensing; + +// Register license before building services +SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + +var builder = WebApplicationBuilder.CreateBuilder(args); + +// Add MVC services +builder.Services.AddControllersWithViews(); + +var app = builder.Build(); + +if (!app.Environment.IsDevelopment()) +{ + app.UseExceptionHandler("/Home/Error"); + app.UseHsts(); +} + +app.UseHttpsRedirection(); +app.UseStaticFiles(); +app.UseRouting(); +app.UseAuthorization(); + +app.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); + +app.Run(); + +{% endhighlight %} +{% endtabs %} + +For detailed licensing instructions, refer to the [Syncfusion Licensing Guide](https://help.syncfusion.com/common/essential-studio/licensing/overview). + +**Step 6: Add UI Button to Index View** + +Open the `Index.cshtml` view file in the Views/Home folder and add a button to trigger PDF generation: {% tabs %} {% highlight CSHTML %} @{ - Html.BeginForm("CreatePDFDocument", "Home", FormMethod.Get); + Html.BeginForm("CreatePDFDocument", "Home", FormMethod.Post); {
@@ -49,136 +121,269 @@ Step 5: A default action method named Index will be present in *HomeController.c {% endtabs %} -Step 6: Include the following namespaces in *HomeController.cs*. +**Step 7: Add Required Namespaces and Create PDF Controller Method** + +Add the following namespaces to your `HomeController.cs` file: {% tabs %} {% highlight c# tabtitle="C#" %} -using Syncfusion.Pdf.Graphics; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Microsoft.AspNetCore.Mvc; using Syncfusion.Drawing; -using Syncfusion.Pdf.Grid; +using Syncfusion.Licensing; using Syncfusion.Pdf; +using Syncfusion.Pdf.Graphics; +using Syncfusion.Pdf.Grid; {% endhighlight %} {% endtabs %} -Step 7: Add a new action method named CreatePDFDocument in HomeController.cs file and include the below code example to generate a PDF document in *HomeController.cs*. +**Step 8: Implement PDF Generation Method** + +Add the following code to generate a PDF document. The method includes error handling, resource disposal patterns, and image asset loading: {% tabs %} {% highlight c# tabtitle="C#" %} -//To load an existing file. -private readonly IWebHostEnvironment _hostingEnvironment; -public HomeController(IWebHostEnvironment hostingEnvironment) +public class HomeController : Controller { - _hostingEnvironment = hostingEnvironment; -} + private readonly IWebHostEnvironment _hostingEnvironment; + private readonly ILogger _logger; -public IActionResult CreatePDFDocument() -{ - //Create a new PDF document. - PdfDocument document = new PdfDocument(); - //Set the page size. - document.PageSettings.Size = PdfPageSize.A4; - //Add a page to the document. - PdfPage page = document.Pages.Add(); - - //Create PDF graphics for the page. - PdfGraphics graphics = page.Graphics; - //Load the image from the disk. - string imagePath = Path.Combine(_hostingEnvironment.WebRootPath, "Data/AdventureCycle.jpg"); - FileStream imageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read); - PdfBitmap image = new PdfBitmap(imageStream); - //Draw an image. - graphics.DrawImage(image, new RectangleF(130, 0, 250, 100)); - - //Draw header text. - graphics.DrawString("Adventure Works Cycles", new PdfStandardFont(PdfFontFamily.TimesRoman, 20, PdfFontStyle.Bold), PdfBrushes.Gray, new PointF(150, 150)); - - //Add paragraph. - string text = "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Washington with 290 employees, several regional sales teams are located throughout their market base."; - //Create a text element with the text and font. - PdfTextElement textElement = new PdfTextElement(text, new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); - //Draw the text in the first column. - textElement.Draw(page, new RectangleF(0, 200, page.GetClientSize().Width, page.GetClientSize().Height)); - - //Create a PdfGrid. - PdfGrid pdfGrid = new PdfGrid(); - //Add values to the list. - List data = new List(); - Object row1 = new { Product_ID = "1001", Product_Name = "Bicycle", Price = "10,000" }; - Object row2 = new { Product_ID = "1002", Product_Name = "Head Light", Price = "3,000" }; - Object row3 = new { Product_ID = "1003", Product_Name = "Break wire", Price = "1,500" }; - data.Add(row1); - data.Add(row2); - data.Add(row3); - //Add list to IEnumerable. - IEnumerable dataTable = data; - //Assign data source. - pdfGrid.DataSource = dataTable; - //Apply built-in table style. - pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); - //Draw the grid to the page of PDF document. - pdfGrid.Draw(graphics, new RectangleF(0, 300, page.Size.Width - 80, 0)); - - //Saving the PDF to the MemoryStream. - MemoryStream stream = new MemoryStream(); - document.Save(stream); - //Set the position as '0'. - stream.Position = 0; - //Download the PDF document in the browser. - FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); - fileStreamResult.FileDownloadName = "Sample.pdf"; - return fileStreamResult; + public HomeController(IWebHostEnvironment hostingEnvironment, ILogger logger) + { + _hostingEnvironment = hostingEnvironment; + _logger = logger; + } + + public IActionResult Index() + { + return View(); + } + + [HttpPost] + public IActionResult CreatePDFDocument() + { + try + { + // Create a new PDF document + using (PdfDocument document = new PdfDocument()) + { + // Set page size + document.PageSettings.Size = PdfPageSize.A4; + + // Add a page + PdfPage page = document.Pages.Add(); + PdfGraphics graphics = page.Graphics; + + // Load and draw image + string imagePath = Path.Combine(_hostingEnvironment.WebRootPath, "images/AdventureCycle.jpg"); + if (System.IO.File.Exists(imagePath)) + { + using (FileStream imageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) + { + PdfBitmap image = new PdfBitmap(imageStream); + graphics.DrawImage(image, new RectangleF(130, 0, 250, 100)); + } + } + else + { + _logger.LogWarning($"Image file not found: {imagePath}"); + } + + // Draw header text + PdfStandardFont titleFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20, PdfFontStyle.Bold); + graphics.DrawString("Adventure Works Cycles", titleFont, PdfBrushes.Black, new PointF(150, 150)); + + // Add description paragraph + string text = "Adventure Works Cycles is a multinational manufacturing company that produces metal and composite bicycles for commercial markets across North America, Europe, and Asia. Based in Washington with 290 employees at headquarters, the company operates regional sales teams throughout its market territories."; + PdfTextElement textElement = new PdfTextElement(text, new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); + textElement.Draw(page, new RectangleF(0, 200, page.GetClientSize().Width, page.GetClientSize().Height)); + + // Create product data grid + List data = new List + { + new { Product_ID = "1001", Product_Name = "Bicycle", Price = "$10,000" }, + new { Product_ID = "1002", Product_Name = "Head Light", Price = "$3,000" }, + new { Product_ID = "1003", Product_Name = "Brake Wire", Price = "$1,500" }, + new { Product_ID = "1004", Product_Name = "Pedal Set", Price = "$2,000" }, + new { Product_ID = "1005", Product_Name = "Chain", Price = "$500" } + }; + + // Create and format grid + PdfGrid pdfGrid = new PdfGrid(); + pdfGrid.DataSource = data; + pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); + + // Draw grid on page + pdfGrid.Draw(graphics, new RectangleF(0, 300, page.Size.Width - 80, 0)); + + // Save to memory stream for download + using (MemoryStream stream = new MemoryStream()) + { + document.Save(stream); + stream.Position = 0; + + // Return PDF file for browser download + return File(stream.ToArray(), "application/pdf", "AdventureWorks.pdf"); + } + } + } + catch (Exception ex) + { + _logger.LogError($"Error generating PDF: {ex.Message}"); + return StatusCode(500, new { error = $"PDF generation failed: {ex.Message}" }); + } + } } {% endhighlight %} {% endtabs %} -**Steps to publish as Azure App Service on Windows** +## Deploying to Azure App Service on Windows + +**Step 9: Prepare for Deployment** + +Before publishing to Azure, ensure your application builds successfully locally: + +```bash +dotnet build +dotnet publish -c Release +``` + +**Step 10: Create Publish Profile** + +Right-click the project in Solution Explorer and select **Publish** to open the publish wizard. -Step 1: Right-click the project and select **Publish** option. ![Publish option Image](Azure_images/Azure-app-service-windows/Publish_button.png) -Step 2: Click the **Add a Publish Profile** button. +**Step 11: Add New Publish Profile** + +Click the **Add a Publish Profile** button to create a new deployment configuration. + ![Add a publish profile](Azure_images/Azure-app-service-windows/Publish_profile.png) -Step 3: Select the publish target as **Azure**. +**Step 12: Select Azure as Target** + +Choose **Azure** as your publish target platform. + ![Select the publish target as Azure](Azure_images/Azure-app-service-windows/Select_target.png) -Step 4: Select the Specific target as **Azure App Service (Windows)**. +**Step 13: Select Azure App Service (Windows)** + +Choose **Azure App Service (Windows)** as the specific deployment target. + ![Select the publish target](Azure_images/Azure-app-service-windows/Select_azure-app-service-windows.png) -Step 5: To create a new app service, click **Create new** option. +**Step 14: Create New App Service** + +Click **Create new** to set up a new App Service instance on Windows. + ![Click create new option](Azure_images/Azure-app-service-windows/Create_new_app_service.png) -Step 6: Click the **Create** button to proceed with **App Service** creation. +**Step 15: Configure App Service Plan** + +Click **Create** to proceed with App Service and hosting plan configuration. Select appropriate tier (B1 or higher recommended). + ![Click the create button](Azure_images/Azure-app-service-windows/App_service_details.png) -Step 7: Click the **Finish** button to finalize the **App Service** creation. +**Step 16: Finalize Configuration** + +Click **Finish** to complete the App Service setup wizard. + ![Click the finish button](Azure_images/Azure-app-service-windows/Finish_app_service.png) -Step 8: Click **Close** button. +**Step 17: Review Settings** + +Verify the publish profile configuration and click **Close** to proceed. + ![Create a ASP.NET Core Project](Azure_images/Azure-app-service-windows/profile_creation_success.png) -Step 9: Click the **Publish** button. +**Step 18: Publish Application** + +Click the **Publish** button to deploy your application to Azure App Service on Windows. + ![Click the Publish button](Azure_images/Azure-app-service-windows/Publish_app_service.png) -Step 10: Now, Publish has been succeeded. +**Step 19: Verify Deployment Success** + +Wait for the publish operation to complete. You should see a success message with deployment details. + ![Publish has been succeeded](Azure_images/Azure-app-service-windows/Publish_link.png) -Step 11: Now, the published webpage will open in the browser. +## Testing the Deployed Application + +**Step 20: Launch Browser** + +After successful deployment, your application automatically opens in the browser at `https://.azurewebsites.net`. + ![Browser will open after publish](Azure_images/Azure-app-service-windows/WebView.png) -Step 12: Select the PDF document and Click **Create PDF document** to create a PDF document.You will get the output PDF document as follows. -![Azure App Service on Windows](Azure_images/Azure-app-service-windows/Output.png) +**Step 21: Generate PDF** + +Click the **Create PDF Document** button on the homepage to trigger PDF generation. The PDF will download automatically as `AdventureWorks.pdf`. -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Azure/Azure%20App%20Service). +**Expected Output:** -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +The generated PDF contains: +- Adventure Works Cycles company logo (from image file) +- Title and company description +- Product information in a formatted table +- Professional styling and layout + +![Azure App Service on Windows](Azure_images/Azure-app-service-windows/Output.png) -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| **License Key Not Registered** | Ensure `SyncfusionLicenseProvider.RegisterLicense()` is called in `Program.cs` before building services. The license key is required for all PDF operations. | +| **Image File Not Found** | Verify the image file exists at `wwwroot/images/AdventureCycle.jpg`. Check file permissions and ensure the file is copied to the output directory during deployment. | +| **Syncfusion.Pdf.NET Package Not Found** | Run `dotnet add package Syncfusion.Pdf.NET` or use NuGet Package Manager to install the latest version targeting .NET 6.0+. | +| **PDF Generation Fails with "Access Denied"** | Ensure the web app has write permissions to the temp directory. On Azure App Service Windows, PDFs are created in the app's temporary storage. | +| **"Could not find wwwroot folder"** | Verify the project structure includes a `wwwroot` folder at the project root. If missing, create it and add images to `wwwroot/images/` subdirectory. | +| **Deployment Failed with Authentication Error** | Verify you are logged into Azure: `az login`. Check Azure subscription and ensure you have sufficient permissions to create resources. | +| **Application Timeout on Startup** | If using a Free tier App Service, startup may be slow. Upgrade to B1 or higher tier for better performance. Check Application Insights logs for detailed errors. | +| **PDF Download Not Working** | Verify the controller returns `File()` with correct content type (`application/pdf`). Check browser developer tools for network errors or CORS issues. | +| **Missing Dependencies in Deployment** | Ensure all NuGet packages are restored during deployment. Check Application Insights and deployment logs in Azure portal for detailed build errors. | +| **Memory Issues Generating Large PDFs** | Use streaming instead of buffering entire documents. For very large PDFs, consider Azure Functions with higher memory allocation or upgrading to a larger App Service tier. | + +## Next Steps + +Explore advanced PDF capabilities and Azure integration patterns: + +### Advanced PDF Features +- **[Merge Multiple PDFs](https://help.syncfusion.com/file-formats/pdf/working-with-documents/merge-documents)** — Combine multiple reports into a single document +- **[Split PDF Documents](https://help.syncfusion.com/file-formats/pdf/split-document)** — Extract specific pages or create filtered PDFs +- **[Add Watermarks](https://help.syncfusion.com/file-formats/pdf/working-with-pages/add-watermark)** — Brand PDFs with company logos and confidentiality markers +- **[Create Interactive Forms](https://help.syncfusion.com/file-formats/pdf/working-with-forms/overview)** — Build fillable PDF forms for data collection +- **[Digital Signatures](https://help.syncfusion.com/file-formats/pdf/working-with-forms/create-digital-signatures)** — Sign PDFs programmatically for compliance +- **[PDF Encryption](https://help.syncfusion.com/file-formats/pdf/working-with-forms/encryption)** — Protect sensitive documents with passwords and permissions + +### Azure Integration Patterns +- **[Store PDFs in Azure Blob Storage](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction)** — Scalable storage for generated documents +- **[Monitor with Application Insights](https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview)** — Track PDF generation performance and errors +- **[Auto-scaling Policies](https://learn.microsoft.com/en-us/azure/app-service/manage-scale-up)** — Scale based on demand +- **[CI/CD with Azure Pipelines](https://learn.microsoft.com/en-us/azure/devops/pipelines/overview)** — Automate deployment updates + +## Resources + +**Sample Code:** +- [Complete working sample on GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Azure/Azure%20App%20Service) + +**Documentation:** +- [Syncfusion .NET PDF Library Guide](https://help.syncfusion.com/file-formats/pdf/) +- [Azure App Service Documentation](https://learn.microsoft.com/en-us/azure/app-service/) +- [.NET Documentation](https://learn.microsoft.com/en-us/dotnet/) + +**Try It Out:** +- [Syncfusion PDF Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) +- [Azure Free Account](https://azure.microsoft.com/en-us/free/) \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-Functions-v1.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-Functions-v1.md index b59591c74a..3ac9749d87 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-Functions-v1.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-Functions-v1.md @@ -6,129 +6,251 @@ control: PDF documentation: UG --- -# Create PDF document in Azure Functions v1 +# Create a PDF File in Azure Functions v1 -The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, edit PDF documents programmatically without the dependency of Adobe Acrobat. Using this library, you can **create PDF document in Azure Functions v1**. +> **⚠️ Deprecation Notice**: Azure Functions v1 runtime reached end of life on December 13, 2019. This guide is maintained for legacy applications only. **New projects should use [Azure Functions v4](Create-PDF-document-in-Azure-Functions-v4.md)** with .NET 6.0+ support and improved performance. + +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, edit PDF documents programmatically without the dependency of Adobe Acrobat. Using this library, you can generate PDF documents in Azure Functions v1 runtime. + +## Prerequisites + +| Requirement | Details | +|-------------|---------| +| **IDE** | Visual Studio 2019 or later | +| **.NET Framework Version** | .NET Framework 4.7.2 (Azure Functions v1 runtime) | +| **NuGet Package** | Syncfusion.Pdf.NET v16.2.0.x or later | +| **Azure Subscription** | Required to deploy to Azure | +| **Azure Tools** | Azure Functions Core Tools v1.x or Visual Studio Azure workload | +| **Licensing** | Syncfusion license key (required v16.2.0.x+) | +| **Image Assets** | AdventureCycle.jpg embedded as resource file | + +> **Note**: Azure Functions v1 uses .NET Framework, not .NET Core. For modern deployments, refer to [Azure Functions v4 guide](Create-PDF-document-in-Azure-Functions-v4.md). ## Steps to create a PDF document in Azure Functions v1 -Step 1: Create a new Azure Functions project. -![Create a Azure Functions project](Azure_images/Azure-Functions-V1/Project_creation.png) +### Setting Up the Project + +**Step 1**: Create a new Azure Functions project in Visual Studio by selecting **File > New > Project** and searching for "Azure Functions". + +![Create a new Azure Functions project](Azure_images/Azure-Functions-V1/Project_creation.png) + +**Step 2**: Enter a project name and select the project location, then click **Create**. -Step 2: Create a project name and select the location. ![Create a project name](Azure_images/Azure-Functions-V1/Configuration_project.png) -Step 3: Select function worker as **.NET Framework**. -![Select function worker](Azure_images/Azure-Functions-V1/Additional_information.png) +**Step 3**: In the configuration dialog, select **.NET Framework** as the function runtime worker type. + +![Select function worker as .NET Framework](Azure_images/Azure-Functions-V1/Additional_information.png) + +**Step 4**: Install the [Syncfusion.Pdf.NET](https://www.nuget.org/packages/Syncfusion.Pdf.NET) NuGet package. Use the Package Manager Console or NuGet Package Manager UI to add the latest version. -Step 4: Install the [Syncfusion.PDF.AspNet](https://www.nuget.org/packages/Syncfusion.Pdf.AspNet) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). -![Install Syncfusion.Pdf.AspNet NuGet package](Azure_images/Azure-Functions-V1/NuGet_package_reference.png) +```bash +Install-Package Syncfusion.Pdf.NET +``` -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add "Syncfusion.Licensing" assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to know about registering Syncfusion® license key in your application to use our components. +![Install Syncfusion.Pdf.NET NuGet package](Azure_images/Azure-Functions-V1/NuGet_package_reference.png) -Step 4: Include the following namespaces in the **Function1.cs** file. +**Step 5**: Configure the Syncfusion license key in your Azure Function. Create or update the **Function1.cs** file to include license registration at startup. Add the following in the function's static constructor or at the beginning of the Run method: + +```csharp +static Function1() +{ + // Register license (replace with your actual license key) + Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); +} +``` + +> **Important**: Starting with Syncfusion v16.2.0.x, a license key is required. You can obtain a free community license from [Syncfusion Community License](https://help.syncfusion.com/common/essential-studio/licensing/community-license). See [licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for registration details. + +**Step 6**: Include the following namespaces in the **Function1.cs** file. {% tabs %} -{% highlight c# tabtitle="C#" %} +{% highlight c# tabtitle="Using Statements" %} + +using System; +using System.IO; +using System.Reflection; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using Microsoft.Azure.WebJobs; +using Microsoft.Extensions.Logging; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Grid; -using System.Drawing; {% endhighlight %} + {% endtabs %} -Step 5: Add the following code example in **Run** method of **Function1** class to perform **create a PDF document** in Azure Functions and return the resultant **PDF document**. +**Step 7**: Add the following code example to the **Run** method of the **Function1** class. This generates a PDF document and returns it as an HTTP response for download. {% tabs %} -{% highlight c# tabtitle="C#" %} - -//Create a new PDF document. -PdfDocument document = new PdfDocument(); -//Set the page size. -document.PageSettings.Size = PdfPageSize.A4; -//Add a page to the document. -PdfPage page = document.Pages.Add(); - -//Create PDF graphics for the page. -PdfGraphics graphics = page.Graphics; -//Load the image from the disk. -var assembly = Assembly.GetExecutingAssembly(); -var imageStream = assembly.GetManifestResourceStream("Create-PDF-document.Data.AdventureCycle.jpg"); -PdfBitmap image = new PdfBitmap(imageStream); -//Draw an image. -graphics.DrawImage(image, new RectangleF(130, 0, 250, 100)); - -//Draw header text. -graphics.DrawString("Adventure Works Cycles", new PdfStandardFont(PdfFontFamily.TimesRoman, 20, PdfFontStyle.Bold), PdfBrushes.Gray, new PointF(150, 150)); - -//Add paragraph. -string text = "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Washington with 290 employees, several regional sales teams are located throughout their market base."; -//Create a text element with the text and font. -PdfTextElement textElement = new PdfTextElement(text, new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); -//Draw the text in the first column. -textElement.Draw(page, new RectangleF(0, 200, page.GetClientSize().Width, page.GetClientSize().Height)); - -//Create a PdfGrid. -PdfGrid pdfGrid = new PdfGrid(); -//Add values to the list. -List data = new List(); -Object row1 = new { Product_ID = "1001", Product_Name = "Bicycle", Price = "10,000" }; -Object row2 = new { Product_ID = "1002", Product_Name = "Head Light", Price = "3,000" }; -Object row3 = new { Product_ID = "1003", Product_Name = "Break wire", Price = "1,500" }; -data.Add(row1); -data.Add(row2); -data.Add(row3); -//Add list to IEnumerable. -IEnumerable dataTable = data; -//Assign data source. -pdfGrid.DataSource = dataTable; -//Apply built-in table style. -pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); -//Draw the grid to the page of PDF document. -pdfGrid.Draw(graphics, new RectangleF(0, 300, page.Size.Width - 80, 0)); - -//Save and close the PDF document -MemoryStream ms = new MemoryStream(); -document.Save(ms); -document.Close(); -ms.Position = 0; - -HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); -response.Content = new ByteArrayContent(ms.ToArray()); -response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") + +{% highlight c# tabtitle="Function1.cs" %} + +public static class Function1 { - FileName = "Sample.pdf" -}; -response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf"); -return response; + static Function1() + { + // Register Syncfusion license (call once at startup) + Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + } + + [FunctionName("CreatePDFDocument")] + public static HttpResponseMessage Run( + [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, + ILogger log) + { + try + { + log.LogInformation("PDF document generation started."); + + // Create a new PDF document + using (PdfDocument document = new PdfDocument()) + { + // Set page size + document.PageSettings.Size = PdfPageSize.A4; + PdfPage page = document.Pages.Add(); + PdfGraphics graphics = page.Graphics; + + // Load and draw image from embedded resource + Assembly assembly = Assembly.GetExecutingAssembly(); + string resourcePath = "Create-PDF-document.Data.AdventureCycle.jpg"; + + using (Stream imageStream = assembly.GetManifestResourceStream(resourcePath)) + { + if (imageStream != null) + { + using (PdfBitmap image = new PdfBitmap(imageStream)) + { + graphics.DrawImage(image, new RectangleF(130, 0, 250, 100)); + } + } + else + { + log.LogWarning($"Embedded resource not found: {resourcePath}"); + } + } + + // Draw header text + PdfStandardFont titleFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20, PdfFontStyle.Bold); + graphics.DrawString("Adventure Works Cycles", titleFont, PdfBrushes.Black, new PointF(150, 150)); + + // Add description paragraph + string text = "Adventure Works Cycles is a multinational manufacturing company that produces metal and composite bicycles for commercial markets across North America, Europe, and Asia. Based in Washington with 290 employees at headquarters, the company operates regional sales teams throughout its market territories."; + PdfTextElement textElement = new PdfTextElement(text, new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); + textElement.Draw(page, new RectangleF(0, 200, page.GetClientSize().Width, page.GetClientSize().Height)); + + // Create product data grid + List data = new List + { + new { Product_ID = "1001", Product_Name = "Bicycle", Price = "$10,000" }, + new { Product_ID = "1002", Product_Name = "Head Light", Price = "$3,000" }, + new { Product_ID = "1003", Product_Name = "Brake Wire", Price = "$1,500" }, + new { Product_ID = "1004", Product_Name = "Pedal Set", Price = "$2,000" }, + new { Product_ID = "1005", Product_Name = "Chain", Price = "$500" } + }; + + // Create and format grid + PdfGrid pdfGrid = new PdfGrid(); + pdfGrid.DataSource = data; + pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); + pdfGrid.Draw(graphics, new RectangleF(0, 300, page.Size.Width - 80, 0)); + + // Save to memory stream + using (MemoryStream ms = new MemoryStream()) + { + document.Save(ms); + ms.Position = 0; + + // Create HTTP response with PDF attachment + HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); + response.Content = new ByteArrayContent(ms.ToArray()); + response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") + { + FileName = "AdventureWorks.pdf" + }; + response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); + + log.LogInformation("PDF document generated successfully."); + return response; + } + } + } + catch (Exception ex) + { + log.LogError($"Error generating PDF: {ex.Message}\n{ex.StackTrace}"); + return new HttpResponseMessage(HttpStatusCode.InternalServerError) + { + Content = new StringContent($"{{\"error\": \"PDF generation failed: {ex.Message}\"}}") + }; + } + } +} {% endhighlight %} + {% endtabs %} -Step 6: Right click the project and select **Publish**. Then, create a new profile in the Publish Window. +> **Important**: Replace `"YOUR_LICENSE_KEY"` with your actual Syncfusion license key. The resource path `"Create-PDF-document.Data.AdventureCycle.jpg"` assumes the image is embedded in a `Data` folder. Adjust the path based on your project structure. + +### Local Testing + +**Step 8**: Before deploying to Azure, test the function locally using Azure Functions Core Tools. Press **F5** in Visual Studio or run: + +```bash +func start +``` + +The local runtime starts and displays function URLs. Navigate to `http://localhost:7071/api/CreatePDFDocument` in your browser to test PDF generation locally. + +### Deploying to Azure + +**Step 9**: Right-click the project in Solution Explorer and select **Publish** to open the publish profile wizard. + ![Create a new profile in the Publish Window](Azure_images/Azure-Functions-V1/Publish_button.png) -Step 7: Select the target as **Azure** and click **Next** button. +**Step 10**: Select **Azure** as the publish target and click **Next**. + ![Select the target as Azure](Azure_images/Azure-Functions-V1/Set_Azure_target.png) -Step 8: Select the **Create new** button. +**Step 11**: Choose **Create new** to set up a new Function App on Azure. + ![Configure Hosting Plan](Azure_images/Azure-Functions-V1/Function_insane.png) -Step 9: Click **Create** button. +**Step 12**: Click **Create** to configure the Function App name, resource group, and hosting plan. + ![Select the plan type](Azure_images/Azure-Functions-V1/Hosting_sample.png) -Step 10: After creating app service then click **Finish** button. +**Step 13**: After creating the Function App configuration, click **Finish** to finalize. + ![Creating app service](Azure_images/Azure-Functions-V1/Finish_function.png) -Step 11: Click the **Publish** button. +**Step 14**: Click the **Publish** button to deploy your function to Azure. + ![Click Publish Button](Azure_images/Azure-Functions-V1/Click_publish_button.png) -Step 12: Publish has been succeed. -![Publish succeeded](Azure_images/Azure-Functions-V1/Successful_publish.png) +**Step 15**: Wait for publishing to complete. You should see a success message confirming deployment. + +![Publishing succeeded](Azure_images/Azure-Functions-V1/Successful_publish.png) + +### Testing the Deployed Function + +**Step 16**: In the Azure portal, navigate to your Function App and open the **CreatePDFDocument** function. Click **Get Function URL** and copy the full URL. + +**Step 17**: Paste the function URL into a new browser tab and press Enter. The PDF file will download automatically. + +**Expected Output:** + +The generated PDF contains: +- Adventure Works Cycles company logo +- Company name and description +- Product information table with 5 sample items +- Professional formatting and styling -Step 13: Now, go to Azure portal and select the App Services. After running the service, click **Get function URL > Copy**. Include the URL as a query string in the URL. Then, paste it into the new browser tab. You will get the PDF document as follows. -![Output document](Azure_Images/Azure-Functions-V4/Final_output.png) +![Output document](Azure_images/Azure-Functions-V1/Final_output.png) You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Azure/Azure%20Function%20V1). diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-Functions-v4.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-Functions-v4.md index 91bb6caea0..cadfc179f6 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-Functions-v4.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Azure-Functions-v4.md @@ -6,138 +6,293 @@ control: PDF documentation: UG --- -# Create PDF document in Azure Functions v4 +# Create a PDF File in Azure Functions v4 -The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, edit PDF documents programmatically without the dependency of Adobe Acrobat. Using this library, you can **create PDF document in Azure Functions v4**. +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, edit PDF documents programmatically without the dependency of Adobe Acrobat. Using this library, you can generate PDF documents in Azure Functions v4 runtime with modern .NET 6.0+ support. -## Steps to create a PDF document in Azure Functions v4 +## Prerequisites -Step 1: Create a new Azure Functions project. -![Create a Azure Functions project](Azure_images/Azure-Functions-V4/Project_creation.png) +| Requirement | Details | +|-------------|---------| +| **IDE** | Visual Studio 2022 or later | +| **.NET Version** | .NET 8.0 (Long-term support) or .NET 6.0+ | +| **NuGet Package** | Syncfusion.Pdf.NET v16.2.0.x or later | +| **Azure Subscription** | Required to deploy to Azure | +| **Azure Tools** | Azure Functions Core Tools v4.x or Visual Studio Azure workload | +| **Licensing** | Syncfusion license key (required v16.2.0.x+) | +| **Image Assets** | AdventureCycle.jpg embedded as resource file | + +> **Note**: Azure Functions v4 runtime uses modern .NET runtime (.NET 6.0+) with improved performance and features compared to v1. + +## Steps to create a PDF document in Azure Functions v4 + +### Setting Up the Project + +**Step 1**: Create a new Azure Functions project in Visual Studio by selecting **File > New > Project** and searching for "Azure Functions". + +![Create a new Azure Functions project](Azure_images/Azure-Functions-V4/Project_creation.png) + +**Step 2**: Enter a project name and select the project location, then click **Create**. -Step 2: Create a project name and select the location. ![Create a project name](Azure_images/Azure-Functions-V4/Configuration_project.png) -Step 3: Select function worker as **.NET 8.0(Long-term support)**. -![Select function worker](Azure_Images/Azure-Functions-V4/Additional_information.png) +**Step 3**: In the configuration dialog, select **.NET 8.0 (Long-term support)** as the function runtime. + +![Select function worker as .NET 8.0](Azure_images/Azure-Functions-V4/Additional_information.png) + +**Step 4**: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.NET) NuGet package. Use the Package Manager Console or NuGet Package Manager UI. + +```bash +Install-Package Syncfusion.Pdf.NET +``` + +![Install Syncfusion.Pdf.NET NuGet package](Azure_images/Azure-Functions-V4/NuGet_package_reference.png) + +**Step 5**: Configure the Syncfusion license key in your Azure Function. Add the following code to the **Program.cs** file before building services: -Step 4: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core/) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). -![Install Syncfusion.Pdf.AspNet NuGet package](Azure_Images/Azure-Functions-V4/NuGet_package_reference.png) +```csharp +// In Program.cs - add this before var host = builder.Build(); +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); +``` -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add "Syncfusion.Licensing" assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to know about registering Syncfusion® license key in your application to use our components. +> **Important**: Starting with Syncfusion v16.2.0.x, a license key is required. Obtain a free community license from [Syncfusion Community License](https://help.syncfusion.com/common/essential-studio/licensing/community-license). See [licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for registration details. -Step 4: Include the following namespaces in the **Function1.cs** file. +**Step 6**: Include the following namespaces in the **Function1.cs** file. {% tabs %} {% highlight c# tabtitle="C#" %} +using System; +using System.IO; +using System.Reflection; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using Microsoft.Azure.Functions.Worker; +using Microsoft.Azure.Functions.Worker.Http; +using Microsoft.Extensions.Logging; +using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Grid; -using Syncfusion.Pdf; using Syncfusion.Drawing; {% endhighlight %} + {% endtabs %} -Step 5: Add the following code example in **Run** method of **Function1** class to perform **create a PDF document** in Azure Functions and return the resultant **PDF document**. +**Step 7**: Add the following code example to the **Run** method of the **Function1** class. This generates a PDF document and returns it as an HTTP response for download. {% tabs %} {% highlight c# tabtitle="C#" %} -//Create a new PDF document. -PdfDocument document = new PdfDocument(); -//Set the page size. -document.PageSettings.Size = PdfPageSize.A4; -//Add a page to the document. -PdfPage page = document.Pages.Add(); - -//Create PDF graphics for the page. -PdfGraphics graphics = page.Graphics; -//Load the image from the disk. -var assembly = Assembly.GetExecutingAssembly(); -var imageStream = assembly.GetManifestResourceStream("Create_PDF_document.Data.AdventureCycle.jpg"); -PdfBitmap image = new PdfBitmap(imageStream); -//Draw an image. -graphics.DrawImage(image, new RectangleF(130, 0, 250, 100)); - -//Draw header text. -graphics.DrawString("Adventure Works Cycles", new PdfStandardFont(PdfFontFamily.TimesRoman, 20, PdfFontStyle.Bold), PdfBrushes.Gray, new PointF(150, 150)); - -//Add paragraph. -string text = "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Washington with 290 employees, several regional sales teams are located throughout their market base."; -//Create a text element with the text and font. -PdfTextElement textElement = new PdfTextElement(text, new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); -//Draw the text in the first column. -textElement.Draw(page, new RectangleF(0, 200, page.GetClientSize().Width, page.GetClientSize().Height)); - -//Create a PdfGrid. -PdfGrid pdfGrid = new PdfGrid(); -//Add values to the list. -List data = new List(); -Object row1 = new { Product_ID = "1001", Product_Name = "Bicycle", Price = "10,000" }; -Object row2 = new { Product_ID = "1002", Product_Name = "Head Light", Price = "3,000" }; -Object row3 = new { Product_ID = "1003", Product_Name = "Break wire", Price = "1,500" }; -data.Add(row1); -data.Add(row2); -data.Add(row3); -//Add list to IEnumerable. -IEnumerable dataTable = data; -//Assign data source. -pdfGrid.DataSource = dataTable; -//Apply built-in table style. -pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); -//Draw the grid to the page of PDF document. -pdfGrid.Draw(graphics, new RectangleF(0, 300, page.Size.Width - 80, 0)); - -MemoryStream memoryStream = new MemoryStream(); -//Saves the PDF document file. -document.Save(memoryStream); -//Create the response to return. -HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); -//Set the PDF document saved stream as content of response. -response.Content = new ByteArrayContent(memoryStream.ToArray()); -//Set the contentDisposition as attachment. -response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") +public class Function1 { - FileName = "Sample.pdf" -}; -//Set the content type as PDF document mime type. -response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf"); -//Return the response with output PDF document stream. -return response; + private readonly ILogger _logger; + + public Function1(ILogger logger) + { + _logger = logger; + } + + [Function("CreatePDFDocument")] + public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestData req) + { + try + { + _logger.LogInformation("PDF document generation started."); + + // Create a new PDF document + using (PdfDocument document = new PdfDocument()) + { + // Set page size + document.PageSettings.Size = PdfPageSize.A4; + PdfPage page = document.Pages.Add(); + PdfGraphics graphics = page.Graphics; + + // Load and draw image from embedded resource + Assembly assembly = Assembly.GetExecutingAssembly(); + string resourcePath = "CreatePDFDocument.Data.AdventureCycle.jpg"; + + using (Stream imageStream = assembly.GetManifestResourceStream(resourcePath)) + { + if (imageStream != null) + { + using (PdfBitmap image = new PdfBitmap(imageStream)) + { + graphics.DrawImage(image, new RectangleF(130, 0, 250, 100)); + } + } + else + { + _logger.LogWarning($"Embedded resource not found: {resourcePath}"); + } + } + + // Draw header text + PdfStandardFont titleFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20, PdfFontStyle.Bold); + graphics.DrawString("Adventure Works Cycles", titleFont, PdfBrushes.Black, new PointF(150, 150)); + + // Add description paragraph + string text = "Adventure Works Cycles is a multinational manufacturing company that produces metal and composite bicycles for commercial markets across North America, Europe, and Asia. Based in Washington with 290 employees at headquarters, the company operates regional sales teams throughout its market territories."; + PdfTextElement textElement = new PdfTextElement(text, new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); + textElement.Draw(page, new RectangleF(0, 200, page.GetClientSize().Width, page.GetClientSize().Height)); + + // Create product data grid + List data = new List + { + new { Product_ID = "1001", Product_Name = "Bicycle", Price = "$10,000" }, + new { Product_ID = "1002", Product_Name = "Head Light", Price = "$3,000" }, + new { Product_ID = "1003", Product_Name = "Brake Wire", Price = "$1,500" }, + new { Product_ID = "1004", Product_Name = "Pedal Set", Price = "$2,000" }, + new { Product_ID = "1005", Product_Name = "Chain", Price = "$500" } + }; + + // Create and format grid + PdfGrid pdfGrid = new PdfGrid(); + pdfGrid.DataSource = data; + pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); + pdfGrid.Draw(graphics, new RectangleF(0, 300, page.Size.Width - 80, 0)); + + // Save to memory stream and return as response + using (MemoryStream memoryStream = new MemoryStream()) + { + document.Save(memoryStream); + memoryStream.Position = 0; + + // Create HTTP response with PDF attachment + var response = req.CreateResponse(HttpStatusCode.OK); + response.Headers.Add("Content-Disposition", "attachment; filename=AdventureWorks.pdf"); + response.Headers.Add("Content-Type", "application/pdf"); + response.WriteBytes(memoryStream.ToArray()); + + _logger.LogInformation("PDF document generated successfully."); + return response; + } + } + } + catch (Exception ex) + { + _logger.LogError($"Error generating PDF: {ex.Message}\n{ex.StackTrace}"); + var errorResponse = req.CreateResponse(HttpStatusCode.InternalServerError); + errorResponse.WriteString($"{{\"error\": \"PDF generation failed: {ex.Message}\"}}"); + return errorResponse; + } + } +} {% endhighlight %} + {% endtabs %} -Step 6: Right click the project and select **Publish**. Then, create a new profile in the Publish Window. -![Create a new profile in the Publish Window](Azure_Images/Azure-Functions-V4/Click_publish.png) +> **Important**: Replace `"YOUR_LICENSE_KEY"` in Program.cs with your actual Syncfusion license key. The resource path `"CreatePDFDocument.Data.AdventureCycle.jpg"` assumes the image is embedded in a `Data` folder. Adjust the path based on your project structure. + +### Local Testing + +**Step 8**: Before deploying to Azure, test the function locally using Azure Functions Core Tools. Press **F5** in Visual Studio or run: + +```bash +func start +``` + +The local runtime starts and displays function URLs. Navigate to `http://localhost:7071/api/CreatePDFDocument` in your browser to test PDF generation locally. + +### Deploying to Azure + +**Step 9**: Right-click the project in Solution Explorer and select **Publish** to open the publish profile wizard. + +![Create a new profile in the Publish Window](Azure_images/Azure-Functions-V4/Click_publish.png) + +**Step 10**: Select **Azure** as the publish target and click **Next**. + +![Select the target as Azure](Azure_images/Azure-Functions-V4/Set_Azure_target.png) + +**Step 11**: Choose **Azure Function App (Windows)** as the specific deployment target and click **Next**. + +![Select Azure Function App](Azure_images/Azure-Functions-V4/Select_function_app.png) + +**Step 12**: Click **Create new** to set up a new Function App on Azure. + +![Configure Hosting Plan](Azure_images/Azure-Functions-V4/Select_create_new_button.png) + +**Step 13**: Configure the Function App name, resource group, and hosting plan, then click **Create**. + +![Select the plan type](Azure_images/Azure-Functions-V4/Hosting_plan.png) + +**Step 14**: After creating the Function App configuration, click **Finish** to complete setup. + +![Creating app service](Azure_images/Azure-Functions-V4/Creating_app_service.png) + +**Step 15**: Click **Close** to finalize the publish profile creation. + +![Click close button](Azure_images/Azure-Functions-V4/publish-profile-creation-progress.png) + +**Step 16**: Click the **Publish** button to deploy your function to Azure. + +![Click Publish button](Azure_images/Azure-Functions-V4/successful_publish.png) + +### Testing the Deployed Function + +**Step 17**: Wait for publishing to complete. Navigate to your Function App in the Azure portal. + +**Step 18**: Open the **CreatePDFDocument** function and click **Get Function URL**. Copy the full URL. + +**Step 19**: Paste the function URL into a new browser tab and press Enter. The PDF file will download automatically. + +**Expected Output:** + +The generated PDF contains: +- Adventure Works Cycles company logo +- Company name and description +- Product information table with 5 sample items +- Professional formatting and styling -Step 7: Select the target as **Azure** and click **Next** button. -![Select the target as Azure](Azure_Images/Azure-Functions-V4/Set_Azure_target.png) +![Output document](Azure_images/Azure-Functions-V4/Final_output.png) -Step 8: Select the **Azure Function App (Windows)** and click **Next**. -![Select Azure function app](Azure_Images/Azure-Functions-V4/Select_function_app.png) +## Troubleshooting -Step 9: Select the **Create new** button. -![Configure Hosting Plan](Azure_Images/Azure-Functions-V4/Select_create_new_button.png) +| Issue | Solution | +|-------|----------| +| **License Key Not Registered** | Ensure `SyncfusionLicenseProvider.RegisterLicense()` is called in `Program.cs` before services are built. The license key must be registered at startup for all PDF operations to work. | +| **Embedded Resource Not Found** | Verify the image file is marked as "Embedded Resource" in project properties. Check the resource path matches your project namespace (e.g., "CreatePDFDocument.Data.AdventureCycle.jpg"). | +| **Syncfusion.Pdf.NET Package Not Found** | Run `Install-Package Syncfusion.Pdf.NET` in Package Manager Console. Verify the package version is v16.2.0.x or later for .NET 6.0+ support. | +| **"The name 'req' does not exist" Compile Error** | Azure Functions v4 uses `HttpRequestData` parameter. Ensure the function parameter is named `req` or use `req.CreateResponse()` method for responses. | +| **PDF Generation Fails on Deployment** | Check Azure Function logs in the portal (Monitoring → Logs or Application Insights). Common causes: missing NuGet packages, resource path incorrect, or insufficient permissions. | +| **Function Timeout (5 minutes)** | Large PDF generation can exceed timeout limits. Optimize image sizes, use async operations, or split PDF generation into smaller chunks. | +| **"Access Denied" Error** | Ensure the function app has read permissions for embedded resources. Check Azure App Service file system permissions and resource isolation settings. | +| **Memory Issues with Large PDFs** | Monitor memory usage in Application Insights. For production use, consider Azure Functions Premium Plan with higher memory allocation. Optimize image compression. | +| **Dependency Injection Not Working** | Ensure `ILogger` is properly injected in the constructor. Verify the function is declared as a public class (not static) for DI container support. | +| **Licensing Errors in Production** | License bindings may differ between development and Azure environments. Contact Syncfusion Support for deployment licensing or upgrade to a production license. | -Step 10: Click **Create** button. -![Select the plan type](Azure_Images/Azure-Functions-V4/Hosting_plan.png) +## Next Steps -Step 11: After creating app service then click **Finish** button. -![Creating app service](Azure_Images/Azure-Functions-V4/Creating_app_service.png) +Explore advanced PDF capabilities and Azure integration patterns: -Step 12: Click the **Close** button. -![Click close button](Azure_Images/Azure-Functions-V4/publish-profile-creation-progress.png) +### Advanced PDF Features +- **[Merge Multiple PDFs](https://help.syncfusion.com/file-formats/pdf/working-with-documents/merge-documents)** — Combine multiple reports or documents into a single PDF +- **[Split PDF Documents](https://help.syncfusion.com/file-formats/pdf/split-document)** — Extract specific pages or create filtered PDFs +- **[Add Watermarks](https://help.syncfusion.com/file-formats/pdf/working-with-pages/add-watermark)** — Add company logos, confidentiality markers, or page numbers +- **[Create Interactive Forms](https://help.syncfusion.com/file-formats/pdf/working-with-forms/overview)** — Build fillable PDF forms for data collection +- **[Digital Signatures](https://help.syncfusion.com/file-formats/pdf/working-with-forms/create-digital-signatures)** — Sign PDFs programmatically for compliance +- **[PDF Encryption](https://help.syncfusion.com/file-formats/pdf/working-with-forms/encryption)** — Protect sensitive documents with passwords and permissions -Step 13: Click the **Publish** button. -![Click Publish button](Azure_Images/Azure-Functions-V4/successful_publish.png) +### Azure Integration Patterns +- **[Store PDFs in Azure Blob Storage](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction)** — Scalable storage for generated documents +- **[Trigger from Azure Storage Events](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob)** — Generate PDFs automatically when files are uploaded +- **[Monitor with Application Insights](https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview)** — Track PDF generation performance and errors +- **[Use Azure Queue Storage for Batching](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue)** — Queue PDF generation requests for async processing -Step 13: Now, go to Azure portal and select the App Services. After running the service, click **Get function URL > Copy**. Include the URL as a query string in the URL. Then, paste it into the new browser tab. You will get the PDF document as follows. -![Output document](Azure_Images/Azure-Functions-V4/Final_output.png) +## Resources -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Azure/Azure%20Function%20V4). +**Sample Code:** +- [Complete working sample on GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Azure/Azure%20Function%20V4) -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +**Documentation:** +- [Syncfusion .NET PDF Library Guide](https://help.syncfusion.com/file-formats/pdf/) +- [Azure Functions v4 Runtime Reference](https://learn.microsoft.com/en-us/azure/azure-functions/functions-versions?tabs=v4) +- [Azure Functions Core Tools](https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local) +- [Dependency Injection in Azure Functions](https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection) -An online sample link to [create a PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +**Try It Out:** +- [Syncfusion PDF Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) +- [Azure Free Account](https://azure.microsoft.com/en-us/free/) \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Blazor.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Blazor.md index af0b99e975..7403654184 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Blazor.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Blazor.md @@ -1,21 +1,41 @@ --- -title: Create or Generate PDF file in Blazor | Syncfusion -description: Learn how to create or generate a PDF file in Blazor applications with easy steps using Syncfusion .NET Core PDF library without depending on Adobe. +title: Create a PDF Document in Blazor | Syncfusion +description: Learn how to create a PDF document in Blazor applications with easy steps using Syncfusion .NET PDF library without depending on Adobe. platform: document-processing control: PDF documentation: UG --- -# Create or Generate PDF file in Blazor +# Create a PDF Document in Blazor -The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, work with forms, and secure PDF files. +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create, read, and edit PDF documents in your Blazor applications. It provides advanced features including merging, splitting, stamping documents, managing forms, and securing PDF files with encryption. + +**Requirements:** +- .NET 6 or later +- Blazor Server or Blazor WebAssembly +- Visual Studio 2022 or later To include the Syncfusion® .NET PDF library into your Blazor application, please refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. To quickly get started with creating a PDF document in Blazor, check this video: {% youtube "https://www.youtube.com/watch?v=B5BOBwus0Jc&t=2s" %} -## Steps to create PDF document in Blazor Server application +## Choose Your Platform + +This guide covers multiple Blazor scenarios. Select the one that matches your application type: + +| Platform | When to Use | Bundle Size | Performance | Server Processing | +|----------|------------|------------|-------------|-------------------| +| **Blazor Server** (Recommended) | Full-featured web apps | Small | Fast | Yes | +| **Blazor WebAssembly** | Offline-first, standalone apps | Large | Client-dependent | No | +| **.NET MAUI Blazor** | Cross-platform desktop/mobile | N/A | Native | Yes | +| **Blazor WebAssembly PWA** | Progressive web apps | Large | Client-dependent | No | + +**Recommendation:** Blazor Server (server-side) is recommended to reduce bundle size and improve performance by processing PDFs on the server. + +## Create a PDF Document in Blazor Server Application + +Blazor Server applications process PDFs on the server side, providing better performance and smaller client bundle sizes. Select your IDE below: {% tabcontents %} {% tabcontent Visual Studio %} @@ -39,9 +59,9 @@ By executing the program, you will get the following output in the browser. Click the Export to PDF button, and you will get the PDF document with the following output. ![Blazor server side output PDF document](Create-PDF-Blazor/Blazor_PDF_output.png) -N> We recommend using Blazor Server (server-side) applications to reduce payload and improve performance compared to Blazor WebAssembly (client-side). +## Create a PDF Document in Blazor WebAssembly Application -## Steps to create PDF document in Blazor WASM application +Blazor WebAssembly (WASM) applications run entirely in the browser. PDF generation is handled client-side, which increases bundle size but enables offline functionality. Select your IDE below: {% tabcontents %} {% tabcontent Visual Studio %} @@ -65,7 +85,9 @@ By executing the program, you will get the following output in the browser. Click the Export to PDF button and you will get the PDF document with the following output. ![Blazor getting started output PDF document](Create-PDF-Blazor/Blazor_PDF_output.png) -## Steps to create PDF documents in .NET MAUI Blazor application +## Create a PDF Document in .NET MAUI Blazor Application + +.NET MAUI Blazor enables cross-platform PDF generation for desktop and mobile apps (Windows, macOS, iOS, Android). PDF generation is handled server-side with platform-specific file saving. Select your IDE below: {% tabcontents %} {% tabcontent Visual Studio %} @@ -89,96 +111,41 @@ By running the program, you will see the output in the browser when you click th Click the `Export to PDF` button to get the PDF document with the following output. ![Blazor getting started output PDF document](Create-PDF-Blazor/Blazor_PDF_output.png) -**Save the PDF document on different platforms** +## Platform-Specific Implementation for MAUI + +To save PDF files on different platforms, implement a `SaveService` class with platform-specific partial methods for Android, iOS, macOS, and Windows. + +### Step 1: Create the SaveService Class -Create a folder named `Services`, then add a class called `SaveService.cs` within this folder, and insert the following code into it. +Create a folder named `Services` in your project root (alongside the `Platforms` folder), then add a class called `SaveService.cs` with the following base partial class definition: +> **Note:** Partial classes allow platform-specific implementations in separate files within the `Platforms` folder. {% tabs %} {% highlight c# tabtitle="C#" %} +using System.IO; + public partial class SaveService { - //Method to save document as a file and view the saved document. + //Partial method to save document as a file and view the saved document. + //Implementation is platform-specific (Android, iOS, macOS, Windows). public partial void SaveAndView(string filename, string contentType, MemoryStream stream); } {% endhighlight %} {% endtabs %} -Now, we need to implement platform-specific code to save the PDF document. - -**Android** +### Step 2: Implement Platform-Specific Code -Create a new class file named `SaveAndroid.cs` within the Android folder and add the following code to enable file saving on the Android platform. +Create partial implementations for each platform within the `Platforms` folder. -{% tabs %} -{% highlight c# tabtitle="C#" %} +#### Android Implementation -public partial void SaveAndView(string filename, string contentType, MemoryStream stream) -{ - string exception = string.Empty; - string? root = null; +Create a new class file named `SaveService.cs` within the `Platforms/Android` folder and add the following code to enable file saving on the Android platform: - if (Android.OS.Environment.IsExternalStorageEmulated) - { - root = Android.App.Application.Context!.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads)!.AbsolutePath; - } - else - root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); +**Step 1: Add Android Permissions Configuration** - Java.IO.File myDir = new(root + "/Syncfusion"); - myDir.Mkdir(); - - Java.IO.File file = new(myDir, filename); - - if (file.Exists()) - { - file.Delete(); - } - - try - { - FileOutputStream outs = new(file); - outs.Write(stream.ToArray()); - - outs.Flush(); - outs.Close(); - } - catch (Exception e) - { - exception = e.ToString(); - } - if (file.Exists()) - { - - if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.N) - { - var fileUri = AndroidX.Core.Content.FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file); - var intent = new Intent(Intent.ActionView); - intent.SetData(fileUri); - intent.AddFlags(ActivityFlags.NewTask); - intent.AddFlags(ActivityFlags.GrantReadUriPermission); - Android.App.Application.Context.StartActivity(intent); - } - else - { - var fileUri = Android.Net.Uri.Parse(file.AbsolutePath); - var intent = new Intent(Intent.ActionView); - intent.SetDataAndType(fileUri, contentType); - intent = Intent.CreateChooser(intent, "Open File"); - intent!.AddFlags(ActivityFlags.NewTask); - Android.App.Application.Context.StartActivity(intent); - } - - } -} - -{% endhighlight %} -{% endtabs %} - -N> Android introduced a new runtime permission model for SDK version 23 and above. Include the following code to enable the Android file provider to save and view the generated PDF document. - -1. Create a new XML file with the name of `file_paths.xml` under the Android project Resources/xml folder and add the following code in it. +Create a new XML file named `file_paths.xml` in the `Android/Resources/xml` folder (create the `xml` folder if it doesn't exist): {% tabs %} {% highlight XML %} @@ -205,213 +172,325 @@ N> Android introduced a new runtime permission model for SDK version 23 and abov {% endhighlight %} {% endtabs %} -2. Add the following code to the `AndroidManifest.xml` file located under Properties/AndroidManifest.xml. +**Step 2: Update Android Manifest** + +Add the following provider configuration to `Platforms/Android/AndroidManifest.xml` within the `` tag: {% tabs %} {% highlight XML %} - - - - - - - - - - + + + + + + + + + {% endhighlight %} {% endtabs %} -**iOS** +> **Note:** The `${applicationId}` placeholder is automatically replaced by the build system; do not edit manually. Android 6.0 (API 23+) requires runtime permissions; FileProvider handles secure file access. + +**Step 3: Create SaveService Implementation** -Create a new class file named `SaveIOS.cs` within the iOS folder and include the following code to enable file saving on the iOS platform. +Create the Android platform-specific SaveService class: {% tabs %} {% highlight c# tabtitle="C#" %} -public partial void SaveAndView(string filename, string contentType, MemoryStream stream) +using Android.App; +using Android.Content; +using Android.OS; +using AndroidX.Core.Content; +using Java.IO; +using System.IO; + +partial class SaveService { - string exception = string.Empty; - string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); - string filePath = Path.Combine(path, filename); - try - { - FileStream fileStream = File.Open(filePath, FileMode.Create); - stream.Position = 0; - stream.CopyTo(fileStream); - fileStream.Flush(); - fileStream.Close(); - } - catch (Exception e) + public partial void SaveAndView(string filename, string contentType, MemoryStream stream) { - exception = e.ToString(); + string exception = string.Empty; + string? root = null; + + // Determine storage location: downloads folder for emulated storage, or MyDocuments otherwise + if (Android.OS.Environment.IsExternalStorageEmulated) + { + root = Application.Context!.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads)!.AbsolutePath; + } + else + { + root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); + } + + Java.IO.File myDir = new(root + "/Syncfusion"); + myDir.Mkdir(); + + Java.IO.File file = new(myDir, filename); + + if (file.Exists()) + { + file.Delete(); + } + + try + { + FileOutputStream outs = new(file); + outs.Write(stream.ToArray()); + outs.Flush(); + outs.Close(); + } + catch (Exception e) + { + exception = e.ToString(); + } + + if (file.Exists()) + { + // Android 7.0+ requires FileProvider for secure file access; older versions use direct URI + if (Build.VERSION.SdkInt >= BuildVersionCodes.N) + { + var fileUri = FileProvider.GetUriForFile(Application.Context, Application.Context.PackageName + ".provider", file); + var intent = new Intent(Intent.ActionView); + intent.SetData(fileUri); + intent.AddFlags(ActivityFlags.NewTask); + intent.AddFlags(ActivityFlags.GrantReadUriPermission); + Application.Context.StartActivity(intent); + } + else + { + var fileUri = Android.Net.Uri.Parse(file.AbsolutePath); + var intent = new Intent(Intent.ActionView); + intent.SetDataAndType(fileUri, contentType); + intent = Intent.CreateChooser(intent, "Open File"); + intent!.AddFlags(ActivityFlags.NewTask); + Application.Context.StartActivity(intent); + } + } } - if (contentType != "application/html" || exception == string.Empty) +} + +{% endhighlight %} +{% endtabs %} + +#### iOS Implementation + +Create a new class file named `SaveService.cs` within the `Platforms/iOS` folder and include the following code to enable file saving on the iOS platform: + +> **Note:** Requires QuickLook framework for document preview. Add to `Info.plist`: `NSLocalizedDescriptionPDF files` for file access description. + +{% tabs %} +{% highlight c# tabtitle="C#" %} + +using Foundation; +using UIKit; +using QuickLook; +using System.IO; + +partial class SaveService +{ + public partial void SaveAndView(string filename, string contentType, MemoryStream stream) { - UIViewController? currentController = UIApplication.SharedApplication!.KeyWindow!.RootViewController; - while (currentController!.PresentedViewController != null) - currentController = currentController.PresentedViewController; - - QLPreviewController qlPreview = new(); - QLPreviewItem item = new QLPreviewItemBundle(filename, filePath); - qlPreview.DataSource = new PreviewControllerDS(item); - currentController.PresentViewController((UIViewController)qlPreview, true, null); + string exception = string.Empty; + string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); + string filePath = Path.Combine(path, filename); + + try + { + FileStream fileStream = File.Open(filePath, FileMode.Create); + stream.Position = 0; + stream.CopyTo(fileStream); + fileStream.Flush(); + fileStream.Close(); + } + catch (Exception e) + { + exception = e.ToString(); + } + + if (contentType != "application/html" && exception == string.Empty) + { + UIViewController? currentController = UIApplication.SharedApplication!.KeyWindow!.RootViewController; + while (currentController?.PresentedViewController != null) + { + currentController = currentController.PresentedViewController; + } + + if (currentController != null) + { + QLPreviewController qlPreview = new(); + QLPreviewItem item = new QLPreviewItemBundle(filename, filePath); + qlPreview.DataSource = new PreviewControllerDS(item); + currentController.PresentViewController(qlPreview, true, null); + } + } } } {% endhighlight %} {% endtabs %} -**MacOS** +#### macOS Implementation -Create a new class file named `SaveMac.cs` within the MacCatalyst folder and include the following code to enable file saving on the macOS platform. +Create a new class file named `SaveService.cs` within the `Platforms/MacCatalyst` folder and include the following code to enable file saving on the macOS platform: {% tabs %} {% highlight c# tabtitle="C#" %} -public partial void SaveAndView(string filename, string contentType, MemoryStream stream) +using Foundation; +using UIKit; +using QuickLook; +using System.IO; + +partial class SaveService { - string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - string filePath = Path.Combine(path, filename); - stream.Position = 0; - //Saves the document - using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.ReadWrite); - stream.CopyTo(fileStream); - fileStream.Flush(); - fileStream.Dispose(); - - UIWindow? window = GetKeyWindow(); - if (window != null && window.RootViewController != null) + public partial void SaveAndView(string filename, string contentType, MemoryStream stream) { - UIViewController? uiViewController = window.RootViewController; - if (uiViewController != null) + string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + string filePath = Path.Combine(path, filename); + stream.Position = 0; + + // Save the document to file system + using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.ReadWrite); + stream.CopyTo(fileStream); + fileStream.Flush(); + fileStream.Dispose(); + + UIWindow? window = GetKeyWindow(); + if (window?.RootViewController != null) { + UIViewController uiViewController = window.RootViewController; QLPreviewController qlPreview = new(); QLPreviewItem item = new QLPreviewItemBundle(filename, filePath); qlPreview.DataSource = new PreviewControllerDS(item); - uiViewController.PresentViewController((UIViewController)qlPreview, true, null); + uiViewController.PresentViewController(qlPreview, true, null); } } -} -public UIWindow? GetKeyWindow() -{ - foreach (var scene in UIApplication.SharedApplication.ConnectedScenes) + private UIWindow? GetKeyWindow() { - if (scene is UIWindowScene windowScene) + // Find the active window in the current scene + foreach (var scene in UIApplication.SharedApplication.ConnectedScenes) { - foreach (var window in windowScene.Windows) + if (scene is UIWindowScene windowScene) { - if (window.IsKeyWindow) + foreach (var window in windowScene.Windows) { - return window; + if (window.IsKeyWindow) + { + return window; + } } } } + return null; } - - return null; } {% endhighlight %} {% endtabs %} -**Windows** +#### Windows Implementation + +Create a new class file named `SaveService.cs` within the `Platforms/Windows` folder and include the following code to enable file saving on the Windows platform: -Create a new class file named `SaveWindows.cs` within the Windows folder and include the following code to enable file saving on the Windows platform. +> **Note:** The async method is required for FileSavePicker dialog interaction on Windows. Works in desktop/Windows App scenarios; may not work in all cloud hosting environments. {% tabs %} {% highlight c# tabtitle="C#" %} -public async partial void SaveAndView(string filename, string contentType, MemoryStream stream) +using Microsoft.Win32.SafeHandles; +using Windows.Foundation.Metadata; +using Windows.Storage; +using Windows.Storage.Pickers; +using Windows.Storage.Streams; +using Windows.UI.Popups; +using Windows.System; +using System.IO; + +partial class SaveService +{ + public async partial void SaveAndView(string filename, string contentType, MemoryStream stream) { StorageFile stFile; string extension = Path.GetExtension(filename); - //Gets process windows handle to open the dialog in application process. + + // Gets the process window handle to open the dialog in the application's process IntPtr windowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; - if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) + + if (!ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) { - //Creates file save picker to save a file. + // Create file save picker to save the document FileSavePicker savePicker = new(); - if (extension == ".xlsx") - { - savePicker.DefaultFileExtension = ".xlsx"; - savePicker.SuggestedFileName = filename; - //Saves the file as xlsx file. - savePicker.FileTypeChoices.Add("XLSX", new List() { ".xlsx" }); - } - if (extension == ".docx") - { - savePicker.DefaultFileExtension = ".docx"; - savePicker.SuggestedFileName = filename; - //Saves the file as Docx file. - savePicker.FileTypeChoices.Add("DOCX", new List() { ".docx" }); - } - else if (extension == ".doc") + + // Configure file type choices based on extension + switch (extension.ToLower()) { - savePicker.DefaultFileExtension = ".doc"; - savePicker.SuggestedFileName = filename; - //Saves the file as Doc file. - savePicker.FileTypeChoices.Add("DOC", new List() { ".doc" }); - } - else if (extension == ".rtf") - { - savePicker.DefaultFileExtension = ".rtf"; - savePicker.SuggestedFileName = filename; - //Saves the file as Rtf file. - savePicker.FileTypeChoices.Add("RTF", new List() { ".rtf" }); - } - else if (extension == ".pdf") - { - savePicker.DefaultFileExtension = ".pdf"; - savePicker.SuggestedFileName = filename; - //Saves the file as Pdf file. - savePicker.FileTypeChoices.Add("PDF", new List() { ".pdf" }); - } - else if (extension == ".pptx") - { - savePicker.DefaultFileExtension = ".pptx"; - savePicker.SuggestedFileName = filename; - //Saves the file as pptx file. - savePicker.FileTypeChoices.Add("PPTX", new List() { ".pptx" }); - } - else if (extension == ".png") - { - savePicker.DefaultFileExtension = ".png"; - savePicker.SuggestedFileName = filename; - //Saves the file as png file. - savePicker.FileTypeChoices.Add("PNG", new List() { ".png" }); + case ".xlsx": + savePicker.DefaultFileExtension = ".xlsx"; + savePicker.FileTypeChoices.Add("XLSX", new List { ".xlsx" }); + break; + case ".docx": + savePicker.DefaultFileExtension = ".docx"; + savePicker.FileTypeChoices.Add("DOCX", new List { ".docx" }); + break; + case ".doc": + savePicker.DefaultFileExtension = ".doc"; + savePicker.FileTypeChoices.Add("DOC", new List { ".doc" }); + break; + case ".rtf": + savePicker.DefaultFileExtension = ".rtf"; + savePicker.FileTypeChoices.Add("RTF", new List { ".rtf" }); + break; + case ".pdf": + savePicker.DefaultFileExtension = ".pdf"; + savePicker.FileTypeChoices.Add("PDF", new List { ".pdf" }); + break; + case ".pptx": + savePicker.DefaultFileExtension = ".pptx"; + savePicker.FileTypeChoices.Add("PPTX", new List { ".pptx" }); + break; + case ".png": + savePicker.DefaultFileExtension = ".png"; + savePicker.FileTypeChoices.Add("PNG", new List { ".png" }); + break; + default: + savePicker.FileTypeChoices.Add("Files", new List { "*" }); + break; } + savePicker.SuggestedFileName = filename; WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle); stFile = await savePicker.PickSaveFileAsync(); } else { + // Fallback: Save to local app folder on mobile platforms StorageFolder local = ApplicationData.Current.LocalFolder; stFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); } + if (stFile != null) { - using (IRandomAccessStream zipStream = await stFile.OpenAsync(FileAccessMode.ReadWrite)) + // Write the stream to the storage file + using (IRandomAccessStream fileStream = await stFile.OpenAsync(FileAccessMode.ReadWrite)) { - //Writes compressed data from memory to file. - using Stream outstream = zipStream.AsStreamForWrite(); + using Stream outstream = fileStream.AsStreamForWrite(); outstream.SetLength(0); - //Saves the stream as file. byte[] buffer = stream.ToArray(); outstream.Write(buffer, 0, buffer.Length); outstream.Flush(); } - //Create message dialog box. + + // Show dialog asking if user wants to view the document MessageDialog msgDialog = new("Do you want to view the document?", "File has been created successfully"); UICommand yesCmd = new("Yes"); msgDialog.Commands.Add(yesCmd); @@ -419,13 +498,12 @@ public async partial void SaveAndView(string filename, string contentType, Memor msgDialog.Commands.Add(noCmd); WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle); - - //Showing a dialog box. IUICommand cmd = await msgDialog.ShowAsync(); + if (cmd.Label == yesCmd.Label) { - //Launch the saved file. - await Windows.System.Launcher.LaunchFileAsync(stFile); + // Launch the saved file with default application + await Launcher.LaunchFileAsync(stFile); } } } @@ -433,9 +511,11 @@ public async partial void SaveAndView(string filename, string contentType, Memor {% endhighlight %} {% endtabs %} -The helper files mentioned above are available on [this](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/create-pdf-file-in-maui#helper-files-for-net-maui) page. +For additional MAUI helper files and utilities, see the [MAUI PDF guide](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/create-pdf-file-in-maui#helper-files-for-net-maui). -## Steps to create PDF documents in Blazor WebAssembly PWA +## Create a PDF Document in Blazor WebAssembly PWA + +Progressive Web Apps (PWA) combine the best of web and native apps, enabling offline functionality. PDF generation in PWA Blazor WebAssembly is client-side and allows saving to device storage or browser cache. Select your IDE below: {% tabcontents %} {% tabcontent Visual Studio %} @@ -457,9 +537,25 @@ You can download a complete working sample from [GitHub](https://github.com/Sync By executing the program, you will get the following output in the browser. ![Blazor WASM PWA browser](Create-PDF-Blazor/Blazor-PWA-4.png) -Click the `Create PDF document` button, and you will get the PDF document with the following output. +Click the `Create PDF document` button to generate and download the PDF. + ![Blazor getting started output PDF document](Create-PDF-Blazor/Blazor_PDF_output.png) -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| "NuGet package not found" | Verify NuGet source is configured correctly; check package version compatibility with your .NET version | +| "Handler method not found" in Blazor | Ensure the button's `@onclick` handler matches the C# method name exactly (case-sensitive) | +| PDF file not downloading (Server/WASM) | Check browser download settings and firewall restrictions; verify HttpContext is available | +| MAUI platform implementation not called | Ensure SaveService partial class exists in `Services` folder; platform-specific files in correct `Platforms/[OS]` subfolder | +| Android "Permission denied" errors | Verify file_paths.xml is in Android/Resources/xml folder; check AndroidManifest.xml has required permissions | +| iOS preview not showing | Ensure QLPreviewController import; verify Info.plist contains file access usage descriptions | +| Windows FileSavePicker not opening | Verify WinRT.Interop is initialized with correct window handle; not supported in all hosting scenarios | +| "Licensing" errors at runtime | Ensure Syncfusion.Licensing NuGet package is installed and license key is registered in your application | + +## Next Steps -An online sample to get started with creating a PDF document is available [here](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +- **Download [Complete Working Samples](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Blazor)** — Reference implementations for all Blazor platforms +- **Try [Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind)** — Interactive PDF generation examples +- **Explore [Syncfusion PDF Library Features](https://www.syncfusion.com/document-sdk/net-pdf-library)** — Complete API reference and advanced capabilities \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Docker.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Docker.md index 6b7a0bccec..c1751f0812 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Docker.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Docker.md @@ -1,35 +1,50 @@ --- -title: Create PDF Files in a Docker Environment | Syncfusion -description: Learn how to create PDF files in a Docker environment using Syncfusion and a containerized .NET application. +title: Create a PDF File in Docker | Syncfusion +description: Learn how to create PDF files in a Docker container using Syncfusion and a containerized .NET Core application. platform: document-processing control: PDF documentation: UG -keywords: docker getting started, docker sample project, container basics, docker tutorial, docker setup, run docker app, docker beginner guide +keywords: docker getting started, docker sample project, container basics, docker tutorial, docker setup, run docker app, containerized pdf --- -# Create PDF Files in a Docker Environment +# Create a PDF File in Docker The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is a powerful and versatile solution for creating, reading, and editing PDF documents in .NET applications. It also provides advanced features such as merging and splitting PDFs, adding stamps, working with form fields, and securing PDF files with encryption and permissions. -To integrate the .NET PDF library into your Docker application, refer to the official documentation sections on [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) for step-by-step guidance. +## Prerequisites -## Steps to Create PDF Files in a Docker Container +| Item | Details | +| --- | --- | +| **Operating System** | Windows, macOS, or Linux (with Docker Desktop installed) | +| **.NET Version** | .NET 5.0 or later (.NET 6.0+ recommended) | +| **Development Environment** | Visual Studio 2022 or Visual Studio Code with C# extension | +| **Docker** | Docker Desktop 3.0 or later (or Docker Engine 20.10+ on Linux) | +| **NuGet Package** | Syncfusion.Pdf.NET (latest version) | +| **License** | Syncfusion license key (required for production use) | + +To integrate the .NET PDF library into your Docker application, ensure you have the Syncfusion NuGet package installed. Refer to the official documentation sections on [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) for additional guidance. + +## Steps to Create a PDF File in a Docker Container + +**Step 1:** Create a new ASP.NET Core MVC application. -Step 1: Create a new ASP.NET Core MVC application. ![Create ASP.NET MVC Web application in Visual Studio](GettingStarted_images/Docker-Image1.png) -Step 2: In the project configuration window, name your project and select Next. +**Step 2:** In the project configuration window, name your project and select Next. + ![Configuration Window](GettingStarted_images/Docker-Image2.png) -Step 3: Enable the Docker support with Linux as a target OS. +**Step 3:** Enable Docker support with Linux as the target OS. This will automatically create a Dockerfile and docker-compose configuration files in your project. + ![Docker Support Window](GettingStarted_images/Docker-Image3.png) -Step 4: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core) NuGet package as a reference to your .NET Standard applications from [NuGet.org](https://www.nuget.org/). +**Step 4:** Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). + ![NuGet Package](GettingStarted_images/Docker-Image4.png) -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add "Syncfusion.Licensing" assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to know about registering Syncfusion® license key in your application to use our components. +**Step 5:** Register the Syncfusion license key in your `Program.cs` file. Starting with v16.2.0.x, Syncfusion assemblies require a license key for production use. Refer to the [Syncfusion licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for detailed instructions on registering your license key. -Step 5: A default action method named Index will be present in `HomeController.cs`. Right-click on this Index method and select Go To View where you will be directed to its associated view page `Index.cshtml`. Add a new button in the `Index.cshtml` as follows. +**Step 6:** A default action method named Index will be present in `HomeController.cs`. Right-click on this Index method and select "Go To View" to open the associated view page `Index.cshtml`. Add a button to trigger PDF generation as follows: {% tabs %} {% highlight CSHTML %} @@ -46,57 +61,86 @@ Step 5: A default action method named Index will be present in `HomeController.c {% endhighlight %} {% endtabs %} -Step 6: The [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) object represents an entire PDF document that is being created. The [PdfTextElement](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfTextElement.html) is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The [PdfGrid](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Grid.PdfGrid.html) allows you to create table by entering data manually or from an external data sources. +**Step 7:** The [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) object represents an entire PDF document. The [PdfTextElement](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfTextElement.html) adds text to a PDF document, and the [PdfGrid](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Grid.PdfGrid.html) creates tables from data. -Add the following code sample in ``ExportService`` class which illustrates how to create a simple PDF document using ``PdfTextElement`` and ``PdfGrid``. +Add the following code to your `HomeController.cs` to create a PDF document with sample weather forecast data: {% tabs %} {% highlight c# tabtitle="C#" %} -public ActionResult CreatePDF() +using Syncfusion.Pdf; +using Syncfusion.Pdf.Graphics; +using Syncfusion.Drawing; +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.AspNetCore.Mvc; + +public class HomeController : Controller { - // Create a new PDF document. - using (PdfDocument pdfDocument = new PdfDocument()) + public IActionResult CreatePDF() { - int paragraphAfterSpacing = 8; - int cellMargin = 8; - - // Add page to the PDF document. - PdfPage page = pdfDocument.Pages.Add(); - // Create title and description. - PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16); - PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black); - PdfLayoutResult result = title.Draw(page, new PointF(0, 0)); - - PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12); - PdfTextElement content = new PdfTextElement( - "This component demonstrates fetching data from a service and exporting the data to a PDF document using Syncfusion .NET PDF library.", - contentFont, - PdfBrushes.Black); - PdfLayoutFormat format = new PdfLayoutFormat + try { - Layout = PdfLayoutType.Paginate - }; - result = content.Draw( - page, - new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), - format); - // Create and style the PDF grid. - PdfGrid pdfGrid = new PdfGrid(); - pdfGrid.Style.CellPadding.Left = cellMargin; - pdfGrid.Style.CellPadding.Right = cellMargin; - pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1); - // Assign data source. - pdfGrid.DataSource = forecasts; - pdfGrid.Style.Font = contentFont; - // Draw PDF grid into the PDF page. - pdfGrid.Draw(page, new PointF(0, result.Bounds.Bottom + paragraphAfterSpacing)); - using (MemoryStream stream = new MemoryStream()) + // Create a new PDF document + using (PdfDocument pdfDocument = new PdfDocument()) + { + int paragraphAfterSpacing = 8; + int cellMargin = 8; + + // Add page to the PDF document + PdfPage page = pdfDocument.Pages.Add(); + + // Create title + PdfStandardFont titleFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 16); + PdfTextElement title = new PdfTextElement("Weather Forecast Report", titleFont, PdfBrushes.Black); + PdfLayoutResult result = title.Draw(page, new PointF(0, 0)); + + // Create description text + PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12); + PdfTextElement content = new PdfTextElement( + "This report demonstrates creating a PDF document with sample weather forecast data using the Syncfusion .NET PDF library in a Docker containerized environment.", + contentFont, + PdfBrushes.Black); + PdfLayoutFormat format = new PdfLayoutFormat { Layout = PdfLayoutType.Paginate }; + result = content.Draw( + page, + new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), + format); + + // Create sample weather forecast data + List weatherData = new List + { + new { Date = "2026-07-16", Condition = "Sunny", Temperature = "85°F", Humidity = "45%" }, + new { Date = "2026-07-17", Condition = "Partly Cloudy", Temperature = "82°F", Humidity = "50%" }, + new { Date = "2026-07-18", Condition = "Rainy", Temperature = "75°F", Humidity = "70%" }, + new { Date = "2026-07-19", Condition = "Cloudy", Temperature = "78°F", Humidity = "60%" } + }; + + // Create and style the PDF grid + PdfGrid pdfGrid = new PdfGrid(); + pdfGrid.Style.CellPadding.Left = cellMargin; + pdfGrid.Style.CellPadding.Right = cellMargin; + pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1); + pdfGrid.DataSource = weatherData; + pdfGrid.Style.Font = contentFont; + + // Draw the grid on the page + pdfGrid.Draw(page, new PointF(0, result.Bounds.Bottom + paragraphAfterSpacing)); + + // Save the PDF to a memory stream + using (MemoryStream stream = new MemoryStream()) + { + pdfDocument.Save(stream); + stream.Position = 0; + return File(stream.ToArray(), "application/pdf", "WeatherForecast.pdf"); + } + } + } + catch (Exception ex) { - // Save the PDF document into the stream. - pdfDocument.Save(stream); - - return File(stream.ToArray(), "application/pdf", "Output.pdf"); + Console.WriteLine($"Error creating PDF: {ex.Message}"); + return BadRequest("Failed to generate PDF document"); } } } @@ -104,13 +148,87 @@ public ActionResult CreatePDF() {% endhighlight %} {% endtabs %} -Step 7: Build and run the sample in Docker. It will pull the Linux Docker image from the Docker hub and run the project. Now, the webpage will open in the browser. Click the button to convert the webpage to a PDF. +**Step 8:** Build the Docker image and run the container. Use the following commands in the terminal/PowerShell from your project root directory: + +{% tabs %} +{% highlight bash tabtitle="Docker Commands" %} + +# Build the Docker image +docker build -t create-pdf-docker . + +# Run the container and map port 80 +docker run -d -p 8080:80 --name pdf-app create-pdf-docker + +# Verify the container is running +docker ps + +{% endhighlight %} +{% endtabs %} + +**Step 9:** Access the application in your browser by navigating to `http://localhost:8080`. Click the "Generate PDF Document" button to create the weather forecast PDF. The PDF file will be downloaded to your computer. -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Docker/Create-PDF-using-Docker). +**Step 10:** To stop and remove the container when finished, use: + +{% tabs %} +{% highlight bash %} + +docker stop pdf-app +docker rm pdf-app + +{% endhighlight %} +{% endtabs %} + +## Output + +Upon successful execution, you will receive a PDF document containing: +- Title: "Weather Forecast Report" +- Description paragraph about the PDF generation +- A formatted data table with sample weather information (Date, Condition, Temperature, Humidity) +- Professional styling applied via GridTable4Accent1 style -By executing the program, you will get a PDF document as follows. ![Docker Output](GettingStarted_images/Docker-Output.png) -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +A complete working sample can be downloaded from the [GitHub repository](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Docker/Create-PDF-using-Docker). + +## Docker Architecture Overview + +When you enable Docker support in Visual Studio: +1. A **Dockerfile** is created that defines the Docker image (OS, runtime, dependencies) +2. The **.NET application** is built inside the container using the Dockerfile instructions +3. The **container** runs the compiled application on Linux +4. The **port mapping** (8080:80) allows your local machine to communicate with the containerized application + +The PDF generation happens inside the container, and the generated file is returned to your browser for download. + +## Troubleshooting + +| Issue | Solution | +| --- | --- | +| "Docker daemon is not running" | Ensure Docker Desktop is installed and running on your machine | +| "Failed to build image" or "Dockerfile not found" | Verify Docker support was enabled in Visual Studio (Step 3) and Dockerfile exists in project root | +| "Port 8080 is already in use" | Change the port mapping: `docker run -d -p 8081:80 --name pdf-app create-pdf-docker` | +| "Connection refused" when accessing localhost | Verify the container is running: `docker ps`. If not listed, check logs: `docker logs pdf-app` | +| "License key is missing" or "License expired" | Register your Syncfusion license key in Program.cs (Step 5) before the application starts | +| "Syncfusion.Pdf.NET not found" | Ensure NuGet package is installed in the project and restored: `dotnet restore` | +| "PDF file not downloaded after clicking button" | Check browser console for errors and verify HomeController.CreatePDF() method returns successfully | +| "Image file not found in container" | If using custom images, copy them to the project and verify they're included in the Docker build context | +| Container exits immediately after start | Check logs for startup errors: `docker logs pdf-app`. Verify license registration in Program.cs | +| "The network request failed" when running in container | Ensure port mapping is correct and firewall allows Docker network traffic | + +## Next Steps + +Explore advanced features and deployment patterns with the Syncfusion .NET PDF library: + +- [Merge PDF Documents](./merge-pdf-documents.md) - Combine multiple PDF files into one +- [Split PDF Documents](./split-pdf-documents.md) - Extract or divide PDF pages +- [Add Watermarks](./add-watermark.md) - Apply text and image watermarks to PDFs +- [Work with Forms](./fill-form-fields.md) - Create and fill interactive PDF forms +- [Add Digital Signatures](./digital-signatures.md) - Sign PDFs digitally +- [Secure Documents](./encrypt-pdf.md) - Encrypt and password-protect PDFs +- [Docker Best Practices](https://docs.docker.com/develop/dev-best-practices/) - Optimize Docker images and containers +- [Kubernetes Deployment](./Create-PDF-document-in-AKS-Environment.md) - Scale PDF generation with Kubernetes +- [Production Deployment](https://docs.microsoft.com/aspnet/core/host-and-deploy/docker/) - Deploy containerized .NET applications to production + +For additional examples and comprehensive API documentation, visit the [Syncfusion .NET PDF documentation](https://help.syncfusion.com/document-processing/pdf/overview). -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +You can also explore our [interactive PDF demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) to see the library in action. \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Web-API.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Web-API.md index 148c943128..aa48f601f5 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Web-API.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-document-in-Web-API.md @@ -1,73 +1,136 @@ --- -title: Create or Generate PDF file in ASP.NET Core Web API | Syncfusion -description: Learn how to create a PDF file in ASP.NET Core Web API with easy steps using Syncfusion .NET PDF library without depending on Adobe +title: Create a PDF File in ASP.NET Core Web API | Syncfusion +description: Learn how to create PDF files in ASP.NET Core Web API using Syncfusion .NET PDF library without the dependency on Adobe Acrobat. platform: document-processing control: PDF documentation: ug -keywords: pdf, aspnet core, web api, csharp +keywords: pdf, aspnet core, web api, c#, pdf generation, rest api --- -# Create or Generate PDF file in ASP.NET Core Web API +# Create a PDF File in ASP.NET Core Web API -The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, forms and secure PDF files. +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, work with forms, and secure PDF files. -To include the .NET PDF library into your ASP.NET Core Web API, please refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. +## Prerequisites -## Steps to create PDF document in ASP.NET Core Web API +| Item | Details | +| --- | --- | +| **Development Environment** | Visual Studio 2022 or Visual Studio Code with C# extension | +| **.NET Version** | .NET 6.0 or later (.NET 8.0 recommended for latest features) | +| **NuGet Package** | Syncfusion.Pdf.NET (latest version) | +| **License** | Syncfusion license key (required for production use) | + +To include the .NET PDF library in your ASP.NET Core Web API, refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. + +## Steps to Create PDF Documents in ASP.NET Core Web API + +**Step 1: Create a New ASP.NET Core Web API Project** + +Launch Visual Studio 2022 and create a new ASP.NET Core Web API project with .NET 6.0 or later. -Step 1: Create a new C# ASP.NET Core Web API project. ![Create ASP.NET Core Web API in Visual Studio](MVC_images/Web-API-1.png) -Step 2: In the project configuration windows, name your project and click Create. +**Step 2: Configure Project Settings** + +In the project configuration dialog, enter your project name and click **Create**. + ![Add the project name](MVC_images/Web-API-2.png) -Step 3: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core) NuGet package as a reference to your ASP.NET Core Web API applications from [NuGet.org](https://www.nuget.org/). +**Step 3: Install the Syncfusion PDF Package** + +Install the [Syncfusion.Pdf.NET](https://www.nuget.org/packages/Syncfusion.Pdf.NET) NuGet package from the NuGet Package Manager. This package provides all essential PDF creation and manipulation features. + ![Install PDF NuGet package](MVC_images/Web-API-3.png) -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add "Syncfusion.Licensing" assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to know about registering Syncfusion® license key in your application to use our components. +**Step 4: Register Your Syncfusion License** + +Add your Syncfusion license key registration to the `Program.cs` file at the application startup. License registration is required for all Syncfusion products and must occur before any PDF operations: + +{% tabs %} +{% highlight c# tabtitle="Program.cs" %} + +using Syncfusion.Licensing; + +// Register Syncfusion license (add before building services) +SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + +var builder = WebApplicationBuilder.CreateBuilder(args); + +// ... rest of configuration -Step 4: Add a new API controller empty file in the project. -![Add new class](MVC_images/Web-API-4.png) +{% endhighlight %} +{% endtabs %} + +For detailed licensing instructions, refer to the [Syncfusion Licensing Guide](https://help.syncfusion.com/common/essential-studio/licensing/overview). + +**Step 5: Create the PDF Controller** -Step 5: Include the following namespaces in that `PdfController.cs` file. +Right-click on the Controllers folder in Solution Explorer and add a new controller class named `PdfController.cs`. This controller will contain the API endpoint for PDF generation. + +![Add new controller class](MVC_images/Web-API-4.png) + +**Step 6: Add Required Namespaces and Data Model** + +Configure your `PdfController.cs` with the necessary namespaces and define the data model. Add the following to the controller file: {% tabs %} -{% highlight c# tabtitle="C#" %} +{% highlight c# tabtitle="PdfController.cs" %} +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Microsoft.AspNetCore.Mvc; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Grid; +// Data model for weather forecast +public class WeatherForecast +{ + public DateOnly Date { get; set; } + public int TemperatureC { get; set; } + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + public string Summary { get; set; } +} + {% endhighlight %} {% endtabs %} -Step 6: The [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) object represents an entire PDF document that is being created. The [PdfTextElement](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfTextElement.html) is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The [PdfGrid](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Grid.PdfGrid.html) allows you to create table by entering data manually or from an external data sources. +**Step 7: Implement the PDF Generation Methods** -Add the following code sample in ``PdfController`` class which illustrates how to create a simple PDF document using ``PdfTextElement`` and ``PdfGrid``. +Add the controller class definition and implement the PDF creation methods. The [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) class represents the entire PDF, [PdfTextElement](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfTextElement.html) adds formatted text, and [PdfGrid](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Grid.PdfGrid.html) creates data tables: {% tabs %} -{% highlight c# tabtitle="C#" %} +{% highlight c# tabtitle="PdfController.cs" %} + +private static readonly string[] Summaries = new[] +{ + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" +}; -[HttpGet("/api/Pdf")] +[HttpGet("/api/pdf")] +[Produces("application/pdf")] public IActionResult CreatePdfDocument() { try { - const string fileDownloadName = "Output.pdf"; - const string contentType = "application/pdf"; - var stream = ExportWeatherForecastToPdf(); - stream.Position = 0; - return File(stream, contentType, fileDownloadName); + using (MemoryStream stream = ExportWeatherForecastToPdf()) + { + // Return PDF file for download + return File(stream.ToArray(), "application/pdf", "WeatherForecast.pdf"); + } } catch (Exception ex) { - return BadRequest($"Error occurred while creating PDF file: {ex.Message}"); + return BadRequest(new { error = $"Error occurred while creating PDF: {ex.Message}" }); } } private MemoryStream ExportWeatherForecastToPdf() { + // Generate sample weather forecast data var forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), @@ -75,48 +138,146 @@ private MemoryStream ExportWeatherForecastToPdf() Summary = Summaries[Random.Shared.Next(Summaries.Length)] }).ToList(); + // Create PDF document using (PdfDocument pdfDocument = new PdfDocument()) { - int paragraphAfterSpacing = 8; - int cellMargin = 8; + const int paragraphAfterSpacing = 8; + const int cellMargin = 8; + + // Add a page to the document PdfPage page = pdfDocument.Pages.Add(); - PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16); - PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black); + + // Add title + PdfStandardFont titleFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 16); + PdfTextElement title = new PdfTextElement("Weather Forecast Report", titleFont, PdfBrushes.Black); PdfLayoutResult result = title.Draw(page, new PointF(0, 0)); + + // Add description text PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12); - PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a service and exporting the data to a PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black); - PdfLayoutFormat format = new PdfLayoutFormat - { - Layout = PdfLayoutType.Paginate - }; - result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format); + PdfTextElement content = new PdfTextElement( + "This report demonstrates creating a PDF document with weather forecast data using the Syncfusion .NET PDF library in an ASP.NET Core Web API.", + contentFont, + PdfBrushes.Black); + PdfLayoutFormat format = new PdfLayoutFormat { Layout = PdfLayoutType.Paginate }; + result = content.Draw( + page, + new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), + format); + + // Create and style the data grid PdfGrid pdfGrid = new PdfGrid(); pdfGrid.Style.CellPadding.Left = cellMargin; pdfGrid.Style.CellPadding.Right = cellMargin; pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1); pdfGrid.DataSource = forecasts; pdfGrid.Style.Font = contentFont; + + // Draw the grid on the page pdfGrid.Draw(page, new PointF(0, result.Bounds.Bottom + paragraphAfterSpacing)); - using (MemoryStream stream = new MemoryStream()) - { - pdfDocument.Save(stream); - return new MemoryStream(stream.ToArray()); - } + // Save to memory stream + MemoryStream stream = new MemoryStream(); + pdfDocument.Save(stream); + stream.Position = 0; + return stream; } } {% endhighlight %} {% endtabs %} -Step 7: Navigate to the `Swagger UI`, expand the `GET /api/Pdf` API, click `Execute`, and then download the response output. -![Swagger UI](MVC_images/Web-API-5.png) +## Step 8: View API Endpoint Details + +## API Endpoint Specification + +**Endpoint Details:** + +| Property | Value | +|----------|-------| +| **HTTP Method** | GET | +| **Route** | `/api/pdf` | +| **Content-Type** | `application/pdf` | +| **Response Code** | 200 (Success) / 400 (Bad Request) | +| **File Name** | WeatherForecast.pdf | + +**Example Request:** +```bash +curl -X GET "https://localhost:7001/api/pdf" \ + -H "Accept: application/pdf" \ + -o WeatherForecast.pdf +``` + +**Example Response (Success):** +- Status: 200 OK +- Content-Type: application/pdf +- Body: Binary PDF file data +- Headers Include: `Content-Disposition: attachment; filename="WeatherForecast.pdf"` + +**Example Error Response:** +```json +{ + "error": "Error occurred while creating PDF: License key not registered. Please register a valid license key before creating any PDF documents." +} +``` + +## Step 9: Run and Test the Application + +Launch the application and test the PDF endpoint using Swagger UI: + +1. Press **F5** or run `dotnet run` in the terminal +2. Open your browser to `https://localhost:7001/swagger/index.html` +3. Locate the **GET /api/pdf** endpoint in the Swagger UI +4. Click **Try it out**, then click **Execute** +5. The PDF file downloads automatically as `WeatherForecast.pdf` + +**Expected Output:** + +The generated PDF contains: +- Title: "Weather Forecast Report" +- Description explaining the sample +- Data table with 5 rows of weather forecast information (Date, Temperature, Summary) + +![Swagger UI PDF Endpoint](MVC_images/Web-API-5.png) + +**Downloaded PDF Preview:** + +![Generated PDF Document](MVC_images/Output.png) + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| **NuGet Package Not Found** | Ensure you have added the Syncfusion NuGet feed to your Visual Studio package sources. Verify `Syncfusion.Pdf.NET` version matches your .NET target framework (6.0 or later). | +| **License Key Not Registered** | Add the license registration code in `Program.cs` before service configuration. Verify the license key is valid and not expired. Check Syncfusion license portal for active licenses. | +| **Route Not Found (404)** | Confirm the controller route is correctly defined (`[Route("api/[controller]")]` or `[HttpGet("/api/pdf")]`). Verify the API is included in `Program.cs` with `app.MapControllers()`. | +| **"WeatherForecast" class not defined** | Ensure the `WeatherForecast` class with `Date`, `TemperatureC`, and `Summary` properties is defined in the project. Verify it's in the same namespace or add appropriate using statements. | +| **CORS Error (Access-Control-Allow-Origin)** | Configure CORS in `Program.cs` before `app.Build()`. Add `services.AddCors(options => { options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin()); })` and enable it with `app.UseCors("AllowAll");`. | +| **PDF File Download Not Working** | Verify the response includes `Content-Disposition: attachment` header. Check that MemoryStream is properly positioned (Position = 0) before returning. Ensure Content-Type is `application/pdf`. | +| **Port Already in Use** | Change the port in `Properties/launchSettings.json`. Use `netstat -ano \| findstr :7001` (Windows) or `lsof -i :7001` (Linux/macOS) to find conflicting processes. | +| **Null Reference Exception in PDF Creation** | Verify sample data is properly initialized with `Enumerable.Range()`. Ensure `Summaries` array is defined with at least one value. Check that `Random.Shared` is available (.NET 6.0+). | +| **HTTP 405 Method Not Allowed** | Confirm the endpoint uses correct HTTP method (`[HttpGet]`). Verify the route attribute matches the request URL exactly (case-sensitive for path parameters). | +| **Memory Issues with Large Reports** | Use streaming to MemoryStream instead of buffering entire document. Consider pagination for large datasets. Dispose PdfDocument and MemoryStream properly with using statements. | + +## Next Steps + +Explore advanced PDF features in ASP.NET Core Web API: +- **[Merge Multiple PDFs](https://help.syncfusion.com/file-formats/pdf/working-with-documents/merge-documents)** — Combine multiple PDF documents into a single file +- **[Split PDF Documents](https://help.syncfusion.com/file-formats/pdf/split-document)** — Extract specific pages or ranges from PDF files +- **[Add Watermarks](https://help.syncfusion.com/file-formats/pdf/working-with-pages/add-watermark)** — Apply text or image watermarks to PDF pages +- **[Create Interactive Forms](https://help.syncfusion.com/file-formats/pdf/working-with-forms/overview)** — Add fillable form fields to PDF documents +- **[Digital Signatures](https://help.syncfusion.com/file-formats/pdf/working-with-forms/create-digital-signatures)** — Sign PDFs programmatically for authenticity and compliance +- **[Encryption & Security](https://help.syncfusion.com/file-formats/pdf/working-with-forms/encryption)** — Protect PDFs with passwords and permissions +- **[Generate Tables & Charts](https://help.syncfusion.com/file-formats/pdf/working-with-tables)** — Create structured data tables and embedded visualizations + +For production deployment guidance, see: +- **[Deploy ASP.NET Core to Azure App Service](https://learn.microsoft.com/en-us/azure/app-service/quickstart-dotnetcore)** — Host your API in the cloud +- **[Containerize with Docker](https://help.syncfusion.com/file-formats/pdf/create-pdf-document-in-docker)** — Package your Web API for consistent environments +- **[Performance Optimization](https://learn.microsoft.com/en-us/aspnet/core/performance/performance-best-practices)** — Best practices for high-throughput PDF generation -By executing the program, you will get the PDF document as follows. -![ASP.Net Core output PDF document](MVC_images/Output.png) +## Resources You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Web-API/Web-API-Project). -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +Explore the rich set of Syncfusion® PDF library features in the [.NET PDF Documentation](https://help.syncfusion.com/file-formats/pdf). -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +Try the [online PDF demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) to see capabilities in action. \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-Core.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-Core.md index 6d0cd78db2..22d50c4f24 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-Core.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-Core.md @@ -7,35 +7,113 @@ documentation: UG keywords: .net core create pdf, edit pdf, merge, pdf form, fill form, digital sign, table, c#, dotnet core pdf, asp generate pdf, aspx generate pdf --- -# Create or Generate PDF file in ASP.NET Core +# Create a PDF File in ASP.NET Core The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is a powerful and versatile solution for creating, reading, and editing PDF documents in .NET applications. It also provides advanced features such as merging and splitting PDFs, adding stamps, working with form fields, and securing PDF files with encryption and permissions. -To integrate the .NET PDF library into your ASP.NET Core application, refer to the official documentation sections on [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) for step-by-step guidance. +## Prerequisites -N> Beginning with our Volume 2, 2023 release, we have eliminated the dependency on the System.Drawing.Common package from our Syncfusion.Pdf.Imaging.Net.Core package. Instead, we have introduced SkiaSharp as the alternative library. +| Requirement | Details | +|-------------|---------| +| **IDE** | Visual Studio 2022, Visual Studio Code, or JetBrains Rider | +| **.NET Version** | .NET 6.0+, .NET 7.0, or .NET 8.0 (Long-term support recommended) | +| **NuGet Package** | Syncfusion.Pdf.NET v16.2.0.x or later | +| **ASP.NET Core Version** | ASP.NET Core 6.0+ corresponding to your .NET version | +| **Licensing** | Syncfusion license key (required v16.2.0.x+) | +| **Additional Package** | SkiaSharp for image handling (included with Syncfusion.Pdf.NET) | -## Steps to create PDF document in ASP.NET Core +> **Note**: For detailed package installation guidance, refer to [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. + +## License Registration + +Starting with Syncfusion v16.2.0.x, a license key is required for PDF operations. Register your license in the `Program.cs` file before building services: + +```csharp +// In Program.cs - add this before var app = builder.Build(); +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); +``` + +> **Important**: Obtain a free community license from [Syncfusion Community License](https://help.syncfusion.com/common/essential-studio/licensing/community-license) or refer to [licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for production keys. + +> **Note**: As of 2023, Syncfusion eliminated the dependency on System.Drawing.Common and introduced SkiaSharp as the image handling library for cross-platform PDF generation support. SkiaSharp is included with Syncfusion.Pdf.NET and provides improved image rendering and performance. + +## Steps to Create a PDF File in ASP.NET Core + +Select your preferred IDE to follow the complete implementation guide: {% tabcontents %} {% tabcontent Visual Studio %} +**Recommended for Windows development.** Complete step-by-step guide for Visual Studio 2022 with integrated debugging and NuGet management. {% include_relative tabcontent-support/Create-PDF-document-in-ASP-NET-Core-Visual-Studio.md %} {% endtabcontent %} {% tabcontent Visual Studio Code %} +**Cross-platform option** for Windows, macOS, and Linux. Lightweight development environment using CLI tools and extensions. {% include_relative tabcontent-support/Create-PDF-document-in-ASP-NET-Core-VS-Code.md %} {% endtabcontent %} {% tabcontent JetBrains Rider %} +**Cross-platform IDE** with advanced debugging, refactoring, and productivity features. Works on Windows, macOS, and Linux. {% include_relative tabcontent-support/Create-PDF-document-in-ASP-NET-Core-JetBrains.md %} {% endtabcontent %} {% endtabcontents %} -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/ASP.NET%20Core/Create-new-PDF-document). +## Expected Output + +When you execute the application, it generates a PDF document containing: +- Header text with "Adventure Works Cycles" company name +- Company description and information +- Product information table with sample data +- Professional formatting and styling + +The generated PDF file is saved to the application's output directory: + +![ASP.NET Core output PDF document](GettingStarted_images/pdf-generation-output.png) + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| **License Key Not Registered** | Ensure `SyncfusionLicenseProvider.RegisterLicense()` is called in `Program.cs` before services are built. The license key must be registered at application startup. | +| **Syncfusion.Pdf.NET Package Not Found** | Run `dotnet add package Syncfusion.Pdf.NET` in your project directory. Verify the package version is v16.2.0.x or later for your .NET version. | +| **"SkiaSharp" assembly not found** | SkiaSharp is a dependency of Syncfusion.Pdf.NET and should install automatically. If missing, run `dotnet restore` to restore all NuGet packages. | +| **.NET Version Compatibility Error** | Verify your project targets .NET 6.0 or higher. Check `TargetFramework` in your `.csproj` file or use `dotnet --version` to confirm your installed .NET SDK. | +| **PDF File Not Generated** | Check that the file path is valid and writable. Ensure IWebHostEnvironment (for web apps) or correct path is used for saving PDFs. Verify folder permissions. | +| **Missing Assembly References** | Restore NuGet packages by running `dotnet restore`. Check project file includes correct package version targeting your .NET version. | +| **Image Not Displaying in PDF** | Verify image file path is correct and accessible. For embedded resources, check the namespace and file properties (Build Action: Embedded Resource). | +| **Application Startup Timeout** | Large PDF generation can delay startup. Move PDF generation to a background task or async operation. Monitor performance in Application Insights. | +| **Licensing Error in Production** | License key is development-bound. For production, use a production license key or contact Syncfusion Support for deployment licensing guidance. | +| **Performance Issues with Large PDFs** | Optimize image sizes and compression. Use streaming for very large documents. Consider upgrading to higher server specifications. | + +## Next Steps + +Explore advanced PDF capabilities and deployment patterns: + +### Advanced PDF Features +- **[Merge Multiple PDFs](https://help.syncfusion.com/file-formats/pdf/working-with-documents/merge-documents)** — Combine multiple reports or documents into a single file +- **[Split PDF Documents](https://help.syncfusion.com/file-formats/pdf/split-document)** — Extract specific pages or create filtered PDFs +- **[Add Watermarks](https://help.syncfusion.com/file-formats/pdf/working-with-pages/add-watermark)** — Add company logos, confidentiality markers, or page numbers +- **[Create Interactive Forms](https://help.syncfusion.com/file-formats/pdf/working-with-forms/overview)** — Build fillable PDF forms for data collection +- **[Digital Signatures](https://help.syncfusion.com/file-formats/pdf/working-with-forms/create-digital-signatures)** — Sign PDFs programmatically for compliance +- **[PDF Encryption](https://help.syncfusion.com/file-formats/pdf/working-with-forms/encryption)** — Protect sensitive documents with passwords and permissions + +### Deployment Patterns +- **[Deploy to Azure App Service](Create-PDF-document-in-Azure-App-Service-Windows.md)** — Host your ASP.NET Core PDF application in Azure +- **[Containerize with Docker](Create-PDF-document-in-Docker.md)** — Build container images for scalable deployment +- **[Scale with Azure Functions](Create-PDF-document-in-Azure-Functions-v4.md)** — Serverless PDF generation on-demand +- **[Production Deployment Checklist](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/)** — Best practices for deploying ASP.NET Core applications + +## Resources -By executing the program, you will get the PDF document as follows. -![ASP.Net Core output PDF document](GettingStarted_images/pdf-generation-output.png) +**Sample Code:** +- [Complete working sample on GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/ASP.NET%20Core/Create-new-PDF-document) -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +**Documentation:** +- [Syncfusion .NET PDF Library Guide](https://help.syncfusion.com/file-formats/pdf/) +- [ASP.NET Core Documentation](https://learn.microsoft.com/en-us/aspnet/core/) +- [NuGet Packages Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) +- [Licensing Overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind) in ASP.NET Core. \ No newline at end of file +**Try It Out:** +- [Syncfusion PDF Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) +- [Explore Syncfusion PDF Library Features](https://www.syncfusion.com/document-sdk/net-pdf-library) \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-MVC.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-MVC.md index d331dce32f..8d30665b62 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-MVC.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-MVC.md @@ -1,14 +1,18 @@ --- -title: Create or Generate PDF file in ASP.NET MVC | Syncfusion -description: Learn how to create or generate a PDF file in ASP.NET MVC with easy steps using Syncfusion .NET PDF library without depending on Adobe. +title: Create a PDF File in ASP.NET MVC | Syncfusion +description: Learn how to create a PDF file in ASP.NET MVC with easy steps using Syncfusion .NET PDF library without depending on Adobe. platform: document-processing control: PDF documentation: UG keywords: mvc create pdf, mvc generate pdf, edit pdf, merge, pdf form, fill form, digital sign, table, c#, mvc generate pdf --- -# Create or Generate PDF file in ASP.NET MVC +# Create a PDF File in ASP.NET MVC -The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, forms and secure PDF files. +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create, read, and edit PDF documents in your .NET applications. It also provides advanced features such as merging, splitting, stamping documents, managing forms, and securing PDF files with encryption. + +**Requirements:** +- ASP.NET MVC 5 and .NET Framework 4.5 or later +- Visual Studio 2012 or later To include the .NET PDF library into your ASP.NET MVC application, please refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. @@ -24,9 +28,18 @@ Step 2: In the project configuration windows, name your project and click Create Step 3: Install the [Syncfusion.Pdf.AspNet.Mvc5](https://www.nuget.org/packages/Syncfusion.Pdf.AspNet.Mvc5/) NuGet package as a reference to your ASP.NET MVC applications from [NuGet.org](https://www.nuget.org/). ![Install PDF MVC NuGet package](MVC_images/NuGet-package.png) -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add "Syncfusion.Licensing" assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to know about registering Syncfusion® license key in your application to use our components. +**Via Package Manager Console:** +``` +Install-Package Syncfusion.Pdf.AspNet.Mvc5 +``` + +Step 3a: **Licensing Setup (Required)** + +Starting with v16.2.0.x and later, you must register a Syncfusion license key in your application to use the components. Add the "Syncfusion.Licensing" assembly reference and configure your license key. Please refer to the [licensing overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) for step-by-step instructions. -Step 4: A default controller with name `HomeController.cs` gets added on creation of ASP.NET MVC project. Include the following namespaces in that `HomeController.cs` file. +N> Without a valid license key, your application will throw licensing errors at runtime. + +Step 4: A default controller named `HomeController.cs` is created with the ASP.NET MVC project. Add the following namespaces to `HomeController.cs`: {% tabs %} {% highlight c# tabtitle="C#" %} @@ -38,7 +51,7 @@ using System.Drawing; {% endhighlight %} {% endtabs %} -Step 5: A default action method named Index will be present in `HomeController.cs`. Right-click on this Index method and select Go To View where you will be directed to its associated view page `Index.cshtml`. Add a new button in the `Index.cshtml` as follows. +Step 5: A default action method named `Index` exists in `HomeController.cs`. Open the associated view file `Index.cshtml` (either right-click the Index method and select **Go To View**, or navigate to `Views/Home/Index.cshtml` in Solution Explorer). Add the following button to the view: {% tabs %} {% highlight CSHTML %} @@ -55,38 +68,66 @@ Step 5: A default action method named Index will be present in `HomeController.c {% endhighlight %} {% endtabs %} -Step 6: Add a new action method named `CreatePDFDocument` in `HomeController.cs` and include the code example below to generate a PDF document using the [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) class. Then use the [DrawString](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawString_System_String_Syncfusion_Pdf_Graphics_PdfFont_Syncfusion_Pdf_Graphics_PdfBrush_System_Drawing_PointF_) method of the [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html) object to draw text on the PDF page and download the output PDF from the ASP.NET MVC application. +Step 6: Add a new action method named `CreatePDFDocument` in `HomeController.cs`. This method creates a PDF document using the [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) class and draws text using the [DrawString](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawString_System_String_Syncfusion_Pdf_Graphics_PdfFont_Syncfusion_Pdf_Graphics_PdfBrush_System_Drawing_PointF_) method of [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html), then downloads the PDF to the client. {% tabs %} {% highlight c# tabtitle="C#" %} -public ActionResult CreateDocument() +public ActionResult CreatePDFDocument() { - //Create an instance of PdfDocument. - using (PdfDocument document = new PdfDocument()) + try + { + //Create an instance of PdfDocument. + using (PdfDocument document = new PdfDocument()) + { + //Add a page to the document. + PdfPage page = document.Pages.Add(); + //Create PDF graphics for the page. + PdfGraphics graphics = page.Graphics; + //Set the standard font. + PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); + //Draw the text. PointF(0, 0) represents the top-left corner in pixels. + graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); + //Save and send the PDF to the browser for download. + document.Save("Output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save); + } + } + catch (Exception ex) { - //Add a page to the document. - PdfPage page = document.Pages.Add(); - //Create PDF graphics for the page. - PdfGraphics graphics = page.Graphics; - //Set the standard font. - PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); - //Draw the text. - graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); - //Open the document in browser after saving it. - document.Save("Output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save); + ViewBag.Message = "Error generating PDF: " + ex.Message; } - return View(); + return null; } {% endhighlight %} {% endtabs %} -By executing the program, you will get the PDF document as follows. -![ASP.Net Core output PDF document](GettingStarted_images/pdf-generation-output.png) +## Run the Application + +Execute the application and click the **Generate PDF Document** button to create and download the PDF file to your local machine. + +![ASP.NET MVC PDF Generation Output](GettingStarted_images/pdf-generation-output.png) + +## Available Parameters and Options + +**HttpReadType Options:** +- `HttpReadType.Save` — Prompts the user to download the PDF file +- `HttpReadType.Open` — Displays the PDF inline in the browser + +**PdfFont Options:** +You can use different standard fonts: `Helvetica`, `Times New Roman`, `Courier`, `Symbol`, and `ZapfDingbats` + +## Troubleshooting -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/ASP.NET%20MVC/Creating-a-new-PDF-document). +| Issue | Solution | +|-------|----------| +| NuGet package installation fails | Verify your Visual Studio is updated to latest version; check NuGet package source configuration | +| Licensing errors at runtime | Ensure Syncfusion.Licensing assembly is referenced and a valid license key is registered | +| PDF file not downloading | Verify HttpContext.ApplicationInstance.Response is available; check browser's download settings | +| Empty or malformed PDF | Ensure page graphics operations occur before calling Save(); verify fonts are available on the system | -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +## Next Steps -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +- **Download [Complete Working Sample](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/ASP.NET%20MVC/Creating-a-new-PDF-document)** — Reference implementation with additional features +- **Try [Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind)** — Interactive example in your browser +- **Explore [Syncfusion PDF Library Features](https://www.syncfusion.com/document-sdk/net-pdf-library)** — Full documentation and API reference \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-Web-Forms.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-Web-Forms.md index 389d89acd0..2d4b35ba4d 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-Web-Forms.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-ASP-NET-Web-Forms.md @@ -1,41 +1,62 @@ --- -title: Create or Generate PDF file in ASP.NET Web Forms| Syncfusion -description: Learn how to create or generate a PDF file in ASP.NET Web Forms with easy steps using Syncfusion .NET PDF library without depending on Adobe. +title: Create a PDF File in ASP.NET Web Forms| Syncfusion +description: Learn how to create a PDF file in ASP.NET Web Forms with easy steps using Syncfusion .NET PDF library without depending on Adobe. platform: document-processing control: PDF documentation: UG --- -# Create or Generate PDF file in ASP.NET Web Forms +# Create a PDF File in ASP.NET Web Forms -The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, work with forms, and secure PDF files. +> **⚠️ Deprecation Notice:** ASP.NET Web Forms is deprecated. For new projects, consider upgrading to [ASP.NET Core](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/create-pdf-file-in-asp-net-core), which offers modern development practices and better performance. -To include the .NET PDF library into your ASP.NET Web application, please refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create, read, and edit PDF documents. It provides advanced features including merging, splitting, stamping documents, managing forms, and securing PDF files with encryption. -N> This ASP.NET Web Forms platform is deprecated; you can use the same product from the [ASP.NET Core](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/create-pdf-file-in-asp-net-core) platform. +**Requirements:** +- ASP.NET Web Forms with .NET Framework 4.5 or later +- Visual Studio 2012 or later -## Steps to create PDF document in ASP.NET Web Forms +To include the .NET PDF library into your ASP.NET Web application, please refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. +## Project Setup -Step 1: Create a new ASP.NET Web application project. +### Step 1: Create a new ASP.NET Web application project ![ASP.NET Web sample creation step1](Asp.Net_images/Creation1.png) -Step 2: Select the Empty project. +### Step 2: Select the Empty project template ![Select the empty project](Asp.Net_images/Creation2.png) -Step 3: Install the [Syncfusion.Pdf.AspNet](https://www.nuget.org/packages/Syncfusion.Pdf.AspNet/) NuGet package as a reference to your .NET Framework applications from [NuGet.org](https://www.nuget.org/). +### Step 3: Install the Syncfusion.Pdf.AspNet NuGet package + +Install the [Syncfusion.Pdf.AspNet](https://www.nuget.org/packages/Syncfusion.Pdf.AspNet/) NuGet package as a reference to your .NET Framework applications from [NuGet.org](https://www.nuget.org/). + ![PDF ASP.NET NuGet package installation](Asp.Net_images/NuGet-package.png) -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add the `Syncfusion.Licensing` assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to learn about registering the Syncfusion® license key in your application to use our components. +**Via Package Manager Console:** +``` +Install-Package Syncfusion.Pdf.AspNet +``` + +### Step 3a: Configure Licensing (Required) + +Starting with v16.2.0.x and later, you must register a Syncfusion license key to use the components. Add the `Syncfusion.Licensing` assembly reference and configure your license key. Please refer to the [licensing overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) for step-by-step instructions. + +N> Without a valid license key, your application will throw licensing errors at runtime. + +## Create the Web Form + +### Step 4: Add a new Web Form to the project + +Right-click the project in Solution Explorer and select **Add > New Item**. Choose **Web Form** from the templates list and name it `MainPage`. -Step 4: Add a new Web Form in the ASP.NET project. Right-click the project, select **Add > New Item**, and add a Web Form from the list. Name it `MainPage`. +### Step 5: Add a button control to the Web Form -Step 5: Add a new button in the `MainPage.aspx` as follows. +Add the following button to `MainPage.aspx`. The `OnClick="OnButtonClicked"` event handler must match the C# method name in the code-behind file (case-sensitive). {% tabs %} {% highlight HTML %} - + PDF Creation Sample
@@ -49,46 +70,89 @@ Step 5: Add a new button in the `MainPage.aspx` as follows. {% endhighlight %} {% endtabs %} -Step 6: Include the following namespaces in your `MainPage.aspx.cs` file. +## Implement PDF Generation + +### Step 6: Add required namespaces to the code-behind file + +Add the following namespaces to `MainPage.aspx.cs`: {% tabs %} {% highlight c# tabtitle="C#" %} using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; +using System; using System.Drawing; +using System.Web; {% endhighlight %} {% endtabs %} -Step 7: Include the following code example in the click event of the button in `MainPage.aspx.cs` to generate a PDF document using the [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) class. Then use the [DrawString](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawString_System_String_Syncfusion_Pdf_Graphics_PdfFont_Syncfusion_Pdf_Graphics_PdfBrush_System_Drawing_PointF_) method of the [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html) object to draw text on the PDF page. +### Step 7: Add the button click event handler + +Add the following code to the `OnButtonClicked` event handler in `MainPage.aspx.cs`. This creates a PDF document using the [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) class and draws text using the [DrawString](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawString_System_String_Syncfusion_Pdf_Graphics_PdfFont_Syncfusion_Pdf_Graphics_PdfBrush_System_Drawing_PointF_) method of [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html). {% tabs %} {% highlight c# tabtitle="C#" %} -//Create a new PDF document. -using (PdfDocument document = new PdfDocument()) +protected void OnButtonClicked(object sender, EventArgs e) { - //Add a page to the document. - PdfPage page = document.Pages.Add(); - //Create PDF graphics for the page. - PdfGraphics graphics = page.Graphics; - //Set the standard font. - PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); - //Draw the text. - graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); - //Open the document in browser after saving it. - document.Save("Output.pdf", HttpContext.Current.Response, HttpReadType.Save); + try + { + //Create a new PDF document. + using (PdfDocument document = new PdfDocument()) + { + //Add a page to the document. + PdfPage page = document.Pages.Add(); + //Create PDF graphics for the page. + PdfGraphics graphics = page.Graphics; + //Set the standard font. + PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); + //Draw the text. PointF(0, 0) represents the top-left corner in pixels. + graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); + //Save and send the PDF to the browser for download. + //Use HttpReadType.Save for download dialog, HttpReadType.Open for inline display. + document.Save("Output.pdf", HttpContext.Current.Response, HttpReadType.Save); + } + } + catch (Exception ex) + { + Response.Write("Error generating PDF: " + ex.Message); + } } {% endhighlight %} {% endtabs %} -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/ASP.NET). +## Run and Verify + +### Step 8: Run the application + +Build and execute the application. Click the **Create Document** button to generate and download the PDF file to your local machine. + +![ASP.NET Web Forms PDF Generation Output](GettingStarted_images/pdf-generation-output.png) + +## Available Parameters and Options + +**HttpReadType Options:** +- `HttpReadType.Save` — Prompts the user to download the PDF file +- `HttpReadType.Open` — Displays the PDF inline in the browser + +**PdfFont Options:** +You can use different standard fonts: `Helvetica`, `Times New Roman`, `Courier`, `Symbol`, and `ZapfDingbats` + +## Troubleshooting -By executing the program, you will get the PDF document as follows. -![Getting started PDF output document](GettingStarted_images/pdf-generation-output.png) +| Issue | Solution | +|-------|----------| +| NuGet package installation fails | Verify Visual Studio is up to date; check NuGet package source configuration in Tools > Options > NuGet Package Manager | +| Licensing errors at runtime | Ensure Syncfusion.Licensing assembly is referenced and a valid license key is registered | +| PDF file not downloading | Verify HttpContext.Current.Response is available; check browser's download settings and firewall restrictions | +| "Handler 'OnButtonClicked' not found" error | Ensure the event handler method name in code-behind matches exactly (case-sensitive) with the button's OnClick attribute | +| Empty or malformed PDF | Ensure page graphics operations occur before calling Save(); verify required fonts are installed on the system | -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +## Next Steps -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +- **Download [Complete Working Sample](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/ASP.NET)** — Reference implementation with additional features +- **Try [Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind)** — Interactive example in your browser +- **Explore [Syncfusion PDF Library Features](https://www.syncfusion.com/document-sdk/net-pdf-library)** — Complete API reference and advanced capabilities \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS-Elastic-Beanstalk.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS-Elastic-Beanstalk.md index cfb97fcfd6..ae3993cd11 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS-Elastic-Beanstalk.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS-Elastic-Beanstalk.md @@ -7,13 +7,37 @@ documentation: UG keywords: aws elastic beanstalk create pdf, aws edit pdf, merge, pdf form, fill form, digital sign, table, c#, dotnet core pdf, asp generate pdf, aspx generate pdf --- -# Create PDF document in AWS Elastic Beanstalk +# Create a PDF File in AWS Elastic Beanstalk -The [.NET Core PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents programmatically without the dependency of Adobe Acrobat. Using this library, open and save PDF documents in AWS Elastic Beanstalk. +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create, read, and edit PDF documents programmatically in AWS without the dependency of Adobe Acrobat. This guide demonstrates how to generate PDF files using ASP.NET Core applications deployed on AWS Elastic Beanstalk, allowing you to scale PDF operations across multiple instances. -## Steps to create a PDF document in AWS Elastic Beanstalk +## Prerequisites -Step 1: Create a new C# ASP.NET Core Web Application project. +| Requirement | Details | +|-------------|---------| +| **IDE** | Visual Studio 2022 or Visual Studio Code | +| **.NET Version** | .NET 6.0+, .NET 7.0, or .NET 8.0 | +| **ASP.NET Core Version** | ASP.NET Core 6.0+ corresponding to your .NET version | +| **NuGet Package** | Syncfusion.Pdf.NET v16.2.0.x or later | +| **AWS Account** | Active Amazon Web Services account with Elastic Beanstalk access | +| **AWS Tools** | AWS Toolkit for Visual Studio or AWS CLI v2 with configured credentials | +| **Licensing** | Syncfusion license key (required v16.2.0.x+) | +| **Git (optional)** | For CI/CD pipeline deployments to Elastic Beanstalk | + +> **Note**: AWS Elastic Beanstalk provides managed platform-as-a-service (PaaS) for deploying ASP.NET Core applications with automatic scaling and load balancing. This differs from Lambda (serverless) or EC2 (infrastructure) deployments. + +## License Registration + +Starting with Syncfusion v16.2.0.x, a license key is required for PDF operations. Register your license in the `Program.cs` file before building services: + +```csharp +// In Program.cs - add this before var app = builder.Build(); +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); +``` + +> **Important**: Obtain a free community license from [Syncfusion Community License](https://help.syncfusion.com/common/essential-studio/licensing/community-license). For production deployments, store the license key in AWS Secrets Manager or Parameter Store, not hardcoded in source. Refer to [licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for details. + +## Steps to Create a PDF File in AWS Elastic Beanstalk ![ASP.NET Core project](GettingStarted_images/Create-Project.png) Step 2: In configuration windows, name your project and select Next. @@ -21,14 +45,23 @@ Step 2: In configuration windows, name your project and select Next. ![Configuration](GettingStarted_images/AWS-Elastic-Beanstalk-Configuration.png) -Step 3: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core/) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). +Step 3: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.NET) NuGet package. Use the Package Manager Console or NuGet Package Manager UI: + +```bash +dotnet add package Syncfusion.Pdf.NET +``` + ![Install NuGet package](GettingStarted_images/NuGet-Package-AWS-Elastic-Beanstalk.png) -Step 4: A default controller named HomeController.cs gets added to create the ASP.NET Core MVC project. Include the following namespaces in that HomeController.cs file. +Step 4: In the ASP.NET Core MVC project, a default controller named `HomeController.cs` is created. Include the following namespaces in that file: {% tabs %} {% highlight c# tabtitle="C#" %} +using System; +using System.IO; +using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Grid; @@ -36,100 +69,215 @@ using Syncfusion.Pdf.Parsing; using Syncfusion.Drawing; {% endhighlight %} + {% endtabs %} -Step 5: Add a new button in index.cshtml as follows +Step 5: Add a button in `Index.cshtml` to trigger PDF generation. Update the default form to use POST method for file download operations: {% tabs %} {% highlight CSHTML %} @{ -Html.BeginForm("CreatePDF", "Home", FormMethod.Get); -{ -
- -
-
- @ViewBag.Message + Html.BeginForm("CreatePDF", "Home", FormMethod.Post); + { +
+ +
+
+ @ViewBag.Message +
-
-} -Html.EndForm(); + } + Html.EndForm(); } {% endhighlight %} + {% endtabs %} -Step 6: Add a new action method named CreatePDF in HomeController.cs file and include the below code example to generate a PDF document in HomeController.cs. +> **Note**: Use `FormMethod.Post` for operations that generate and download files. The GET method is inappropriate for file downloads and can cause caching issues. + +Step 6: Add a new action method named `CreatePDF` to the `HomeController.cs` file. This method loads an existing PDF, adds a product table to it, and returns the modified PDF for download: {% tabs %} {% highlight c# tabtitle="C#" %} +[HttpPost] public IActionResult CreatePDF() { - //Open an existing PDF document. - FileStream fileStream = new FileStream("Data/Input.pdf", FileMode.Open, FileAccess.Read); - PdfLoadedDocument document = new PdfLoadedDocument(fileStream); - - //Get the first page from a document. - PdfLoadedPage page = document.Pages[0] as PdfLoadedPage; - - //Create PDF graphics for the page. - PdfGraphics graphics = page.Graphics; - - //Create a PdfGrid. - PdfGrid pdfGrid = new PdfGrid(); - //Add values to the list. - List data = new List(); - data.Add(new { Product_ID = "1001", Product_Name = "Bicycle", Price = "10,000" }); - data.Add(new { Product_ID = "1002", Product_Name = "Head Light", Price = "3,000" }); - data.Add(new { Product_ID = "1003", Product_Name = "Break wire", Price = "1,500" }); - - //Assign data source. - pdfGrid.DataSource = data; - - //Apply built-in table style. - pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); - - //Draw the grid to the page of PDF document. - pdfGrid.Draw(graphics, new RectangleF(40, 400, page.Size.Width - 80, 0)); - //Create the memory stream. - MemoryStream stream = new MemoryStream(); - //Save the document to the memory stream. - document.Save(stream); - //Close the document - document.Close(true); - //Return the PDF file as a download - return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "Output.pdf"); + try + { + string inputPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Data", "Input.pdf"); + + // Verify input file exists + if (!System.IO.File.Exists(inputPath)) + { + ViewBag.Message = "Error: Input PDF file not found at " + inputPath; + return View("Index"); + } + + // Open existing PDF document with proper resource disposal + using (FileStream fileStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read)) + { + using (PdfLoadedDocument document = new PdfLoadedDocument(fileStream)) + { + // Get the first page from the document + PdfLoadedPage page = document.Pages[0] as PdfLoadedPage; + PdfGraphics graphics = page.Graphics; + + // Create product data table + List productData = new List + { + new { Product_ID = "1001", Product_Name = "Bicycle", Price = "$10,000" }, + new { Product_ID = "1002", Product_Name = "Head Light", Price = "$3,000" }, + new { Product_ID = "1003", Product_Name = "Brake Wire", Price = "$1,500" }, + new { Product_ID = "1004", Product_Name = "Pedal Set", Price = "$2,000" }, + new { Product_ID = "1005", Product_Name = "Chain", Price = "$500" } + }; + + // Create and format table grid + PdfGrid pdfGrid = new PdfGrid(); + pdfGrid.DataSource = productData; + pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); + + // Draw table on the page + pdfGrid.Draw(graphics, new RectangleF(40, 400, page.Size.Width - 80, 0)); + + // Save to memory stream and return as download + using (MemoryStream stream = new MemoryStream()) + { + document.Save(stream); + stream.Position = 0; + return File(stream.ToArray(), "application/pdf", "Output.pdf"); + } + } + } + } + catch (Exception ex) + { + ViewBag.Message = $"Error generating PDF: {ex.Message}"; + return View("Index"); + } } {% endhighlight %} + {% endtabs %} -Step 7: Click the Publish to AWS Elastic Beanstalk (Legacy) option by right-clicking the project to publish the application in the AWS Elastic Beanstalk environment. +> **Important**: +> - The input PDF file must exist at `wwwroot/Data/Input.pdf` relative to your project root +> - All streams and documents are wrapped in `using` statements for proper resource disposal +> - Error handling ensures graceful failures with user-friendly messages +> - The `[HttpPost]` attribute matches the form method from Step 5 + +### Preparing the Input PDF File + +Before running the application, you need to create the `wwwroot/Data/` directory and add an input PDF: + +1. In Solution Explorer, create the folder structure: **wwwroot → Data** +2. Add or create an `Input.pdf` file in the `Data` folder (sample PDF or your own document) +3. Right-click the PDF file → **Properties** +4. Set **Copy to Output Directory** to "Copy if newer" or "Always copy" + +The folder structure should look like: +``` +your-project/ +├── wwwroot/ +│ ├── Data/ +│ │ └── Input.pdf +│ └── css/ +├── Controllers/ +│ └── HomeController.cs +└── Program.cs +``` + +### Deploying to AWS Elastic Beanstalk + +**Step 7**: Right-click the project in Visual Studio and select **Publish to AWS Elastic Beanstalk**. + ![Publish to AWS Elastic Beanstalk](GettingStarted_images/Publish-AWS-Elastic-Beanstalk.png) -Step 8: Add the AWS profile in the Publish to AWS Elastic Beanstalk Window. After creating the profile, Choose Create a new application environment or Re-deploy to the existing environment. Then, click Next. +**Step 8**: In the "Publish to AWS Elastic Beanstalk" window, select your AWS profile (or create one). Choose either **Create a new application environment** or **Re-deploy to existing environment**, then click **Next**. + ![Publish to AWS Elastic Beanstalk](GettingStarted_images/Publish-to-AWS-Elastic-Beanstalk.png) -Step 9: Click Next from the Application Options window. +**Step 9**: Configure application options (application name, environment name, instance type). Click **Next** to proceed. + ![Application Options Window](GettingStarted_images/Application-Options-Window.png) -Step 10: Click Deploy from the Review window. +**Step 10**: Review the deployment configuration and click **Deploy** to begin publishing. + ![Deploy From the Review Window](GettingStarted_images/Deploy-From-the-Review-Window.png) -Step 11: Click the URL link to launch the application once the Environment is updated successfully and Environment status is healthy. -![Launch Application Window](GettingStarted_images/Launch-Application-Window.png) +**Step 11**: Wait for the environment to be created and reach a healthy state (typically 5-10 minutes). Once complete, click the environment URL to launch your application. -Step 12: Now, the webpage will open in the browser. Click the button to convert the webpage to a PDF document. -![Console Window](GettingStarted_images/Console-Page-AWS-Elastic-Beanstalk.png) - -By executing the program, you will get the PDF document as follows. +![Launch Application Window](GettingStarted_images/Launch-Application-Window.png) -![Open and save a PDF document in AWS Lambda](GettingStarted_images/Output.png) +## Testing the Deployed Application -Users can download the [AWS Elastic Beanstalk](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/AWS/AWSElasticBeanstalk) project from GitHub. +**Step 12**: Your ASP.NET Core application opens in the browser. Click the **Create PDF** button to generate a PDF document from the input file. -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +![Console Window](GettingStarted_images/Console-Page-AWS-Elastic-Beanstalk.png) -An online sample link to [create a PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +**Step 13**: The browser automatically downloads the generated PDF file (`Output.pdf`) containing the modified document with the product table added. + +## Expected Output + +The application generates a PDF file that: +- Loads the input PDF document from `wwwroot/Data/Input.pdf` +- Adds a formatted product table to the first page +- Contains 5 sample products with ID, Name, and Price +- Uses professional table styling +- Downloads to your browser as `Output.pdf` + +![Output PDF document](GettingStarted_images/Output.png) + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| **License Key Not Registered** | Ensure `SyncfusionLicenseProvider.RegisterLicense()` is called in `Program.cs` before services are built. The license key must be set at application startup. | +| **"Input PDF file not found" Error** | Verify the input PDF exists at `wwwroot/Data/Input.pdf`. Check that the file's **Copy to Output Directory** property is set to "Copy if newer" or "Always copy". | +| **Syncfusion.Pdf.NET Package Not Found** | Run `dotnet add package Syncfusion.Pdf.NET` in your project directory. Verify the package version is v16.2.0.x or later for ASP.NET Core support. | +| **Elastic Beanstalk Environment Timeout** | Environment creation can take 5-15 minutes. Check AWS Console → Elastic Beanstalk → Events tab for deployment progress. If fails, review logs and delete the environment to retry. | +| **Application returns HTTP 500 Error** | Check Elastic Beanstalk logs: AWS Console → Elastic Beanstalk → Logs → Request the last 100 lines. Verify `Program.cs` registers license key correctly. | +| **PDF Download Not Working** | Verify controller method has `[HttpPost]` attribute and form uses `FormMethod.Post`. Check browser developer tools Network tab for errors. | +| **"Build Failed" During Deployment** | Ensure all NuGet packages are restored: run `dotnet restore` locally before publishing. Check build errors in Visual Studio Output window. | +| **File Permissions Error on EC2 Instance** | Elastic Beanstalk EC2 instances run as `ec2-user`. Ensure application has write permissions for wwwroot folder. Check IAM instance role permissions. | +| **Licensing Error After Deployment** | Development license key may not work on AWS instances. For production, use a production license key from Syncfusion or contact Support for deployment guidance. | +| **Slow PDF Generation on Startup** | Elastic Beanstalk may use smaller instance types. Upgrade instance type in Environment Configuration → Instances → Change Instance Type to a larger size. | + +## Next Steps + +Explore advanced PDF capabilities and AWS Elastic Beanstalk patterns: + +### Advanced PDF Features +- **[Merge Multiple PDFs](https://help.syncfusion.com/file-formats/pdf/working-with-documents/merge-documents)** — Combine multiple PDF documents into a single file +- **[Split PDF Documents](https://help.syncfusion.com/file-formats/pdf/split-document)** — Extract specific pages from PDF files +- **[Add Watermarks](https://help.syncfusion.com/file-formats/pdf/working-with-pages/add-watermark)** — Add company logos or confidentiality markers to PDFs +- **[Create Interactive Forms](https://help.syncfusion.com/file-formats/pdf/working-with-forms/overview)** — Build fillable PDF forms for data collection +- **[Digital Signatures](https://help.syncfusion.com/file-formats/pdf/working-with-forms/create-digital-signatures)** — Sign PDFs programmatically for document compliance + +### AWS Elastic Beanstalk Patterns +- **[Auto Scaling Configuration](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/autoscaling.html)** — Scale instances based on demand +- **[Load Balancing](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/load-balancer.html)** — Distribute PDF generation requests across instances +- **[Environment Variables](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-softwareconfiguration.html)** — Store license keys securely (better than hardcoding) +- **[CI/CD Pipeline with CodePipeline](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/tutorials.html)** — Automate deployments on code changes +- **[Monitoring with CloudWatch](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.cloudwatch.html)** — Track application health and PDF generation metrics + +## Resources + +**Sample Code:** +- [Complete AWS Elastic Beanstalk example](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/AWS/AWSElasticBeanstalk) + +**Documentation:** +- [Syncfusion .NET PDF Library Guide](https://help.syncfusion.com/file-formats/pdf/) +- [AWS Elastic Beanstalk Documentation](https://docs.aws.amazon.com/elasticbeanstalk/) +- [Deploying ASP.NET Core to Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-dotnet-core.html) +- [AWS Toolkit for Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/) +- [Licensing Overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) + +**Try It Out:** +- [Syncfusion PDF Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) +- [Explore Syncfusion PDF Features](https://www.syncfusion.com/document-sdk/net-pdf-library) +- [AWS Free Tier](https://aws.amazon.com/free/) — Includes Elastic Beanstalk free usage tier \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS-Lambda.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS-Lambda.md index 790163443a..19cf04fdd6 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS-Lambda.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS-Lambda.md @@ -7,34 +7,75 @@ documentation: UG keywords: aws lambda create pdf, aws edit pdf, merge, pdf form, fill form, digital sign, table, c#, dotnet core pdf, asp generate pdf, aspx generate pdf --- -# Create PDF document in AWS Lambda +# Create a PDF File in AWS Lambda -The [.NET Core PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents programmatically without the dependency of Adobe Acrobat. Using this library, open and save PDF documents in AWS Lambda. +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create, read, and edit PDF documents programmatically in AWS Lambda without the dependency of Adobe Acrobat. This guide demonstrates how to generate and process PDF files in serverless AWS Lambda functions, allowing you to scale PDF operations without managing infrastructure. -**Steps to create a PDF document in AWS Lambda** +## Prerequisites + +| Requirement | Details | +|-------------|---------| +| **IDE** | Visual Studio 2022 or Visual Studio Code | +| **.NET Version** | .NET 6.0+, .NET 7.0, or .NET 8.0 | +| **Lambda Runtime** | .NET 6 (supports x86_64 architecture) or newer | +| **NuGet Package** | Syncfusion.Pdf.NET v16.2.0.x or later | +| **AWS Account** | Active Amazon Web Services account with Lambda access | +| **AWS Toolkit** | AWS Toolkit for Visual Studio or AWS CLI v2 with configured credentials | +| **Licensing** | Syncfusion license key (required v16.2.0.x+) | +| **IAM Permissions** | Lambda execution role with `logs:CreateLogGroup`, `logs:CreateLogStream`, `logs:PutLogEvents` for CloudWatch logging | + +> **Note**: AWS Lambda provides serverless compute for PDF generation with automatic scaling. This guide covers local Lambda development and deployment. For request/response workflows, a client console application is also provided. + +## License Registration + +Starting with Syncfusion v16.2.0.x, a license key is required for PDF operations. Add the following to your Lambda function initialization: + +```csharp +// In Function.cs - add before PDF operations +static Function() +{ + Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); +} +``` + +> **Important**: Obtain a free community license from [Syncfusion Community License](https://help.syncfusion.com/common/essential-studio/licensing/community-license). For production Lambda functions, store the license key in [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/) or [Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html), never hardcode in source. Refer to [licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for details. + +## Steps to Create a PDF File in AWS Lambda + +**Step 1**: Create a new AWS Lambda project using the AWS Toolkit for Visual Studio. -Step 1: Create a new **AWS Lambda project** as follows. ![AWS Lambda project](GettingStarted_images/AWS_Project.png) -Step 2: Select Blueprint as Empty Function and click **Finish**. +**Step 2**: Select **Blueprint as Empty Function** and click **Finish**. + ![Select Blueprint as Empty Function](GettingStarted_images/Blueprint_AWS.png) -Step 3: Install the [Syncfusion.Pdf.Imaging.Net.Core](https://www.nuget.org/packages?q=Syncfusion.Pdf.Imaging.Net.Core) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). +**Step 3**: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.NET) NuGet package. Use the Package Manager Console: + +```bash +dotnet add package Syncfusion.Pdf.NET +``` + ![Install NuGet package](GettingStarted_images/NuGetPackageAWSLambda.png) -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from the trial setup or the NuGet feed, add the "Syncfusion.Licensing" assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to register the Syncfusion® license key in your application to use our components. +**Step 4**: Create a `Data` folder in your Lambda project and add the input PDF file (`Input.pdf`). This file will be processed by the Lambda function. -Step 4: Create a folder and copy the required data files and include the files in the project. ![Create a folder](GettingStarted_images/Data-Folder.png) -Step 5: Set the copy to output directory to Copy if newer to all the data files. +**Step 5**: Right-click the PDF file in Solution Explorer → **Properties**. Set **Copy to Output Directory** to "Copy if newer" to ensure the file is included in the deployment package. + ![Property change for data files](GettingStarted_images/Document-property-AWS-lambda.png) -Step 6: Include the following namespaces in the **Function.cs** file. +**Step 6**: Open `Function.cs` and include the following namespaces: {% tabs %} {% highlight c# tabtitle="C#" %} +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using Amazon.Lambda.Core; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Drawing; @@ -42,143 +83,295 @@ using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Grid; {% endhighlight %} + {% endtabs %} -step 7: Add the following code in Function.cs to open the PDF document and update in AWS Lambda. +**Step 7**: Add the following code to your `FunctionHandler` method in `Function.cs` to load a PDF, add a product table, and return the modified document as a Base64-encoded string: {% tabs %} + {% highlight c# tabtitle="C#" %} -string filePath = Path.GetFullPath(@"Data/Input.pdf"); -//Open an existing PDF document. -using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) +public string FunctionHandler(ILambdaContext context) { - PdfLoadedDocument document = new PdfLoadedDocument(stream); - - //Get the first page from a document. - PdfLoadedPage page = document.Pages[0] as PdfLoadedPage; - - //Create PDF graphics for the page. - PdfGraphics graphics = page.Graphics; - - //Create a PdfGrid. - PdfGrid pdfGrid = new PdfGrid(); - //Add values to the list. - List data = new List(); - data.Add(new { Product_ID = "1001", Product_Name = "Bicycle", Price = "10,000" }); - data.Add(new { Product_ID = "1002", Product_Name = "Head Light", Price = "3,000" }); - data.Add(new { Product_ID = "1003", Product_Name = "Break wire", Price = "1,500" }); - - //Assign data source. - pdfGrid.DataSource = data; - - //Apply built-in table style. - pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); - - //Draw the grid to the page of PDF document. - pdfGrid.Draw(graphics, new RectangleF(40, 400, page.Size.Width - 80, 0)); - - //Save the document into stream. - MemoryStream memoryStream = new MemoryStream(); - document.Save(memoryStream); - //Close the document. - document.Close(true); - //return the stream as base64 string - return Convert.ToBase64String(memoryStream.ToArray()); + try + { + // Get the path to the input PDF file in the Lambda deployment package + string dataPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Data", "Input.pdf"); + + if (!System.IO.File.Exists(dataPath)) + { + context.Logger.LogLine($"Error: Input PDF file not found at {dataPath}"); + return "Error: Input PDF file not found"; + } + + // Open the input PDF with proper resource disposal + using (FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read)) + { + using (PdfLoadedDocument document = new PdfLoadedDocument(fileStream)) + { + // Get the first page and its graphics context + PdfLoadedPage page = document.Pages[0] as PdfLoadedPage; + PdfGraphics graphics = page.Graphics; + + // Create product data list + List productData = new List + { + new { Product_ID = "1001", Product_Name = "Bicycle", Price = "$10,000" }, + new { Product_ID = "1002", Product_Name = "Head Light", Price = "$3,000" }, + new { Product_ID = "1003", Product_Name = "Brake Wire", Price = "$1,500" }, + new { Product_ID = "1004", Product_Name = "Pedal Set", Price = "$2,000" }, + new { Product_ID = "1005", Product_Name = "Chain", Price = "$500" } + }; + + // Create and configure grid table + PdfGrid pdfGrid = new PdfGrid(); + pdfGrid.DataSource = productData; + pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); + + // Draw table on the page + pdfGrid.Draw(graphics, new RectangleF(40, 400, page.Size.Width - 80, 0)); + + // Save to memory stream and return as Base64 string + using (MemoryStream memoryStream = new MemoryStream()) + { + document.Save(memoryStream); + memoryStream.Position = 0; + string base64Result = Convert.ToBase64String(memoryStream.ToArray()); + context.Logger.LogLine($"PDF generated successfully. Size: {memoryStream.Length} bytes"); + return base64Result; + } + } + } + } + catch (Exception ex) + { + context.Logger.LogLine($"Error generating PDF: {ex.Message}"); + return $"Error: {ex.Message}"; + } } {% endhighlight %} + {% endtabs %} -Step 8: Right-click the project and select Publish to AWS Lambda. +> **Important Notes**: +> - All streams and documents are wrapped in `using` statements for guaranteed resource disposal in the Lambda environment +> - `Assembly.GetExecutingAssembly().Location` correctly resolves the file path in Lambda deployment +> - Error handling with `ILambdaContext.Logger` logs to CloudWatch for debugging +> - The Base64 encoding allows the PDF to be transmitted via Lambda's text-based response + +## Deploying to AWS Lambda + +**Step 8**: Right-click your Lambda project in Visual Studio and select **Publish to AWS Lambda**. + ![Publish to AWS Lambda](GettingStarted_images/Publish.png) -Step 9: Add the AWS profile in the Upload Lambda Function Window. After creating the profile, Choose Create new function or Re-deploy to the existing Lambda function to publish. Then, click Next. +**Step 9**: In the "Upload Lambda Function" window: +- Select or configure your AWS profile (with appropriate credentials) +- Choose **Create new function** to deploy for the first time, or **Re-deploy to existing function** for updates +- Click **Next** to proceed + ![Upload Lambda Function](GettingStarted_images/Upload-Lampda.png) -Step 10: In the Advanced Function Details window, specify the Role Name based on AWS Managed policy. And edit the memory size and Timeout as maximum in Basic settings of the AWS Lambda function. Then, click Upload to deploy your application. -![Advance Function Details](GettingStarted_images/Advanced-AWS.png) +**Step 10**: In the "Advanced Function Details" window: +- **Function Name**: Enter a descriptive name (e.g., `CreatePDFFunction`) +- **IAM Role**: Select or create an execution role with CloudWatch Logs permissions +- **Memory Size**: Set to 512 MB or higher (PDF operations are memory-intensive) +- **Timeout**: Set to 60 seconds or higher to allow sufficient time for PDF processing +- Click **Upload** to deploy your Lambda function -Step 11: See the published Lambda function in the AWS console after deploying the application. -![After deploying the application](GettingStarted_images/AWS-Lambda-Function.png) +![Advanced Function Details](GettingStarted_images/Advanced-AWS.png) +**Step 11**: After deployment, verify the Lambda function was created successfully by checking the AWS Lambda Console. -**Steps to post the request to AWS Lambda** +![Lambda Function Published](GettingStarted_images/AWS-Lambda-Function.png) -Follow these steps to submit a request to the AWS Lambda function. +## Testing the Lambda Function -Step 1: Create a new console project. -![Create a console project](GettingStarted_images/Console-APP.png) +**Step 12**: Navigate to the AWS Lambda Console → select your function → open the **Test** tab. Create a test event and execute the function to verify PDF generation works correctly. Check CloudWatch Logs for output. -step 2: Install the following NuGet packages in your application from [NuGet.org](https://www.nuget.org/). -* [AWSSDK.Core](https://www.nuget.org/packages/AWSSDK.Core/) -* [AWSSDK.Lambda](https://www.nuget.org/packages/AWSSDK.Lambda/) -* [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/) +## Creating a Console Client to Invoke the Lambda Function -![Install Nuget Package](GettingStarted_images/AWSSDKCore-nuget.png) +Optionally, you can create a console application to invoke the Lambda function and retrieve the generated PDF. This demonstrates the full end-to-end workflow. -![Install Nuget Package](GettingStarted_images/AWSSDKLambda-nuget.png) +**Step 13**: Create a new .NET Console project. -![Install Nuget Package](GettingStarted_images/NewtonsoftJson-nuget.png) +![Create a console project](GettingStarted_images/Console-APP.png) -Step 3: Include the following namespaces in Program.cs file. +**Step 14**: Install the required NuGet packages: + +```bash +dotnet add package AWSSDK.Core +dotnet add package AWSSDK.Lambda +dotnet add package Newtonsoft.Json +``` + +![Install NuGet packages](GettingStarted_images/AWSSDKCore-nuget.png) + +**Step 15**: Include the following namespaces in `Program.cs`: {% tabs %} {% highlight c# tabtitle="C#" %} +using System; +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; using Amazon; using Amazon.Lambda; using Amazon.Lambda.Model; using Newtonsoft.Json; -using System.IO; {% endhighlight %} + {% endtabs %} -Step 4: Add the following code sample in Program.cs to invoke the published AWS Lambda function using the function name and access keys. +**Step 16**: Add the following code to invoke the Lambda function securely. Use [AWS credential chain](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-config-creds.html) instead of hardcoded credentials: {% tabs %} + {% highlight c# tabtitle="C#" %} -//Create a new AmazonLambdaClient -AmazonLambdaClient client = new AmazonLambdaClient("awsaccessKeyID", "awsSecreteAccessKey", RegionEndpoint.USEast1); -//Create new InvokeRequest with published function name. -InvokeRequest invoke = new InvokeRequest +public static async Task Main(string[] args) { - FunctionName = "MyNewFunction", //Add your lambda function name here - InvocationType = InvocationType.RequestResponse, - Payload = "\"Test\"" -}; -//Get the InvokeResponse from client InvokeRequest -InvokeResponse response = await client.InvokeAsync(invoke); -//Read the response stream -var stream = new StreamReader(response.Payload); -//Deserialize the response stream -JsonReader reader = new JsonTextReader(stream); -JsonSerializer serializer = new JsonSerializer(); -var responseText = serializer.Deserialize(reader); - -//Convert Base64String into byte array -byte[] bytes = Convert.FromBase64String(responseText.ToString()); - -//Write the byte array into a file -FileStream fileStream = new FileStream("Sample.pdf", FileMode.Create); -fileStream.Write(bytes, 0, bytes.Length); -fileStream.Flush(); -fileStream.Dispose(); - -System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = "Sample.pdf", UseShellExecute = true }); + try + { + // Create Lambda client using default credential chain (IAM role, environment variables, shared credentials) + // Never hardcode access keys in source code + using (AmazonLambdaClient client = new AmazonLambdaClient(RegionEndpoint.USEast1)) + { + // Invoke the Lambda function + InvokeRequest invokeRequest = new InvokeRequest + { + FunctionName = "CreatePDFFunction", // Replace with your Lambda function name + InvocationType = InvocationType.RequestResponse, + Payload = "\"Test\"" // Payload sent to Lambda + }; + + Console.WriteLine("Invoking Lambda function..."); + InvokeResponse response = await client.InvokeAsync(invokeRequest); + + // Read and parse the response + using (StreamReader streamReader = new StreamReader(response.Payload)) + { + string responseText = await streamReader.ReadToEndAsync(); + + // Remove quotes from JSON response + responseText = responseText.Trim('"'); + + if (response.FunctionError != null) + { + Console.WriteLine($"Lambda function error: {responseText}"); + return; + } + + // Convert Base64-encoded PDF back to binary + byte[] pdfBytes = Convert.FromBase64String(responseText); + + // Save PDF to disk + string outputPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Output.pdf"); + using (FileStream fileStream = new FileStream(outputPath, FileMode.Create)) + { + fileStream.Write(pdfBytes, 0, pdfBytes.Length); + } + + Console.WriteLine($"PDF generated successfully and saved to: {outputPath}"); + + // Open the PDF file in default viewer + System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() + { + FileName = outputPath, + UseShellExecute = true + }); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error invoking Lambda: {ex.Message}"); + } +} {% endhighlight %} -{% endtabs %} -By executing the program, you will get the PDF document as follows. - -![Open and save a PDF document in AWS Lambda](GettingStarted_images/Output.png) - -Users can download the [console application](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/AWS/ConsoleApp) and [AWS Lambda](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/AWS/AWSLambdaProject) project from GitHub. - -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +{% endtabs %} -An online sample link to [create a PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +> **Security Best Practices**: +> - **Never hardcode AWS credentials** in source code. Use the AWS credential chain (IAM roles, environment variables, or shared credentials file) +> - Use **AWS Secrets Manager** or **Parameter Store** to manage sensitive data like license keys +> - Grant Lambda execution role only the minimum required permissions (principle of least privilege) +> - Enable CloudWatch Logs for debugging without exposing sensitive information + +## Expected Output + +When you execute the Lambda function or console client, you will generate a PDF document containing: +- The original input PDF document (loaded from `Data/Input.pdf`) +- A formatted table of 5 product records added to the first page +- Professional table styling applied with GridTable4Accent3 style +- The file returned as Base64-encoded string (via Lambda) or saved as `Output.pdf` (via console client) + +![Output PDF document](GettingStarted_images/Output.png) + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| **License Key Not Registered** | Verify the static constructor in `Function.cs` calls `SyncfusionLicenseProvider.RegisterLicense()` before any PDF operations. The license must be registered at function initialization. | +| **"Input PDF file not found" Error** | Ensure `Data/Input.pdf` exists in your Lambda project and **Copy to Output Directory** is set to "Copy if newer". The file must be included in the deployment package. | +| **Syncfusion.Pdf.NET Package Not Found** | Run `dotnet add package Syncfusion.Pdf.NET` to install the latest version. Verify v16.2.0.x or later is installed via `dotnet list package`. | +| **Lambda Function Timeout** | Increase the **Timeout** setting in Step 10 to 60+ seconds. PDF processing requires time proportional to file size and complexity. Check CloudWatch Logs for performance bottlenecks. | +| **"Access Denied" or IAM Role Error** | The Lambda execution role must have `lambda:InvokeFunction` and `logs:*` permissions. Check IAM role policy in AWS Console → Lambda → Function → Configuration → Permissions. | +| **OutOfMemoryException in Lambda** | Increase **Memory Size** in Step 10 to 512 MB or higher. Lambda allocates CPU proportionally to memory; larger PDFs need more resources. Monitor memory usage in CloudWatch Metrics. | +| **Console Client Cannot Connect to AWS** | Configure AWS credentials via AWS CLI (`aws configure`) or set environment variables `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`. Never hardcode credentials in code. | +| **Base64 Decoding Error in Console Client** | Verify the Lambda function returns a valid Base64 string. Check CloudWatch Logs to confirm the PDF was generated successfully before Base64 encoding. | +| **"Build Failed" During Deployment** | Run `dotnet restore` to ensure all NuGet packages are installed. Check Visual Studio Output window for detailed build errors. Verify the project file (.csproj) references are correct. | +| **Licensing Error After Deployment** | Development license keys may not work on AWS Lambda due to environment detection. Use a production license key or obtain a free community license from Syncfusion. For deployment questions, contact Support. | + +## Next Steps + +Explore advanced PDF capabilities and AWS Lambda integration patterns: + +### Advanced PDF Features +- **[Merge Multiple PDFs](https://help.syncfusion.com/file-formats/pdf/working-with-documents/merge-documents)** — Combine multiple PDF documents into a single file +- **[Split PDF Documents](https://help.syncfusion.com/file-formats/pdf/split-document)** — Extract specific pages from PDF files +- **[Add Watermarks](https://help.syncfusion.com/file-formats/pdf/working-with-pages/add-watermark)** — Add company logos or confidentiality markers +- **[Create Interactive Forms](https://help.syncfusion.com/file-formats/pdf/working-with-forms/overview)** — Build fillable PDF forms for data collection +- **[Digital Signatures](https://help.syncfusion.com/file-formats/pdf/working-with-forms/create-digital-signatures)** — Sign PDFs programmatically for document compliance +- **[PDF Encryption](https://help.syncfusion.com/file-formats/pdf/working-with-security/encrypt-pdf)** — Protect PDFs with passwords and permissions + +### AWS Lambda Integration Patterns +- **[API Gateway Integration](https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html)** — Expose Lambda as HTTP endpoints for PDF generation +- **[S3 Event Triggers](https://docs.aws.amazon.com/lambda/latest/dg/with-s3.html)** — Generate PDFs automatically when files are uploaded to S3 +- **[EventBridge Scheduled Rules](https://docs.aws.amazon.com/lambda/latest/dg/services-eventbridge-scheduled-rules.html)** — Schedule batch PDF generation jobs +- **[Lambda Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)** — Package Syncfusion library as a reusable layer +- **[Asynchronous Invocation](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html)** — Handle PDF generation asynchronously with queues (SQS/SNS) +- **[DynamoDB Integration](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html)** — Stream PDF metadata to DynamoDB for tracking/auditing + +### Deployment and Operations +- **[AWS CloudFormation](https://aws.amazon.com/cloudformation/)** — Automate Lambda deployment as Infrastructure-as-Code +- **[AWS SAM (Serverless Application Model)](https://aws.amazon.com/serverless/sam/)** — Deploy serverless applications with simplified templates +- **[CloudWatch Monitoring](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-cloudwatchlogs.html)** — Monitor function duration, memory usage, errors, and throughput +- **[X-Ray Tracing](https://docs.aws.amazon.com/lambda/latest/dg/services-xray.html)** — Trace PDF generation across distributed services +- **[Cost Optimization](https://aws.amazon.com/lambda/pricing/)** — Monitor invocations and memory to optimize Lambda costs + +## Resources + +**Sample Code:** +- [Complete AWS Lambda example](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/AWS/AWSLambdaProject) +- [Console client application](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/AWS/ConsoleApp) + +**Documentation:** +- [Syncfusion .NET PDF Library Guide](https://help.syncfusion.com/file-formats/pdf/) +- [AWS Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/) +- [Deploying .NET Applications to AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/dotnet-handler.html) +- [AWS Toolkit for Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/) +- [AWS SDK for .NET](https://docs.aws.amazon.com/sdk-for-net/) +- [Licensing Overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) + +**Try It Out:** +- [Syncfusion PDF Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) +- [Explore Syncfusion PDF Features](https://www.syncfusion.com/document-sdk/net-pdf-library) +- [AWS Free Tier](https://aws.amazon.com/free/) — Includes free Lambda and CloudWatch usage +- [AWS Lambda Free Tier](https://aws.amazon.com/lambda/pricing/) — 1 million free requests per month \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS.md index 8658cc4bb0..979b8275df 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-AWS.md @@ -7,29 +7,309 @@ documentation: UG keywords: aws create pdf, edit pdf, merge, pdf form, fill form, digital sign, table, c#, dotnet core pdf, asp generate pdf, aspx generate pdf --- -# Create PDF document in Amazon Web Services (AWS) +# Create a PDF File in Amazon Web Services (AWS) -The [.NET Core PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents programmatically without the dependency of Adobe Acrobat. Using this library, you can open and save PDF documents in Amazon Web Services (AWS). +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create, read, and edit PDF documents programmatically in AWS without the dependency of Adobe Acrobat. This guide demonstrates how to generate PDF documents using AWS Lambda serverless functions integrated with S3 for scalable, cost-effective PDF processing. -N> If this is your first time working with Amazon Web Services (AWS), please refer to the dedicated AWS resources. This section explains how to open and save a PDF document in C# using the .NET Core PDF library in AWS. +> **Note**: This guide focuses on AWS Lambda (.NET 6.0+) for serverless PDF generation. For traditional EC2 instance deployment of ASP.NET Core applications, refer to general [ASP.NET Core deployment documentation](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/). For first-time AWS users, see [AWS Getting Started](https://aws.amazon.com/getting-started/) resources. -## Prerequisites +## Prerequisites -* An active **Amazon Web Services (AWS) account** is required. If you don’t have one, please [create an account](https://aws.amazon.com/) before starting. +| Requirement | Details | +|-------------|---------| +| **AWS Account** | Active Amazon Web Services account with billing enabled | +| **IDE** | Visual Studio 2022 or Visual Studio Code with AWS extensions | +| **AWS Tools** | AWS Toolkit for Visual Studio or AWS CLI v2 with configured credentials | +| **.NET Version** | .NET 6.0+, .NET 7.0, or .NET 8.0 (Lambda runtime requirements) | +| **NuGet Package** | Syncfusion.Pdf.NET v16.2.0.x or later | +| **AWS Services** | AWS Lambda (compute), S3 (storage), IAM (permissions) | +| **IAM Permissions** | Lambda execution role with S3 read/write permissions | +| **Licensing** | Syncfusion license key (required v16.2.0.x+) | -* Download and install the **AWS Toolkit** for Visual Studio, you can download the AWS toolkit from this [link](https://aws.amazon.com/visualstudio/). The Toolkit can be installed from Tools or Extension and updates options in Visual Studio. +## AWS Toolkit Installation -## Amazon Web Services (AWS) +**For Visual Studio:** +1. In Visual Studio, go to **Extensions → Manage Extensions** +2. Search for "AWS Toolkit for Visual Studio 2022" +3. Download and install; restart Visual Studio to activate - - - - - - -
-Amazon Web Services (AWS)
-NuGet package name
-AWS Lambda
-{{'[Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core/)' | markdownify}}
-
+**For Visual Studio Code:** +1. Install the "AWS Toolkit" extension from the VS Code Marketplace +2. Configure AWS credentials: Run `aws configure` in terminal and enter AWS Access Key and Secret + +**AWS CLI Setup:** +```bash +# Install AWS CLI v2 +# Visit: https://aws.amazon.com/cli/ + +# Configure credentials +aws configure +# Enter: AWS Access Key ID, Secret Access Key, Region (e.g., us-east-1), Output format (json) +``` + +## License Registration + +Starting with Syncfusion v16.2.0.x, a license key is required. In your Lambda function, register the license before creating PDFs: + +```csharp +// At Lambda handler startup (before creating PdfDocument) +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); +``` + +> **Important**: Store the license key securely using AWS Secrets Manager or Systems Manager Parameter Store. Never hardcode keys in source code. Obtain a free community license from [Syncfusion Community License](https://help.syncfusion.com/common/essential-studio/licensing/community-license). + +## AWS Services Overview + +| AWS Service | Purpose | Details | +|-------------|---------|---------| +| **AWS Lambda** | Compute | Serverless function execution; runs .NET 6.0+ code on-demand | +| **Amazon S3** | Storage | Stores generated PDF documents; integrates with Lambda for input/output | +| **AWS IAM** | Security | Manages permissions; Lambda execution role controls service access | +| **CloudWatch** | Monitoring | Logs Lambda execution details; tracks errors and performance | + +## Creating PDF in AWS Lambda + +### Step 1: Set Up AWS Lambda IAM Role + +Create an IAM role for Lambda with S3 and CloudWatch permissions: + +1. Go to **AWS Console → IAM → Roles → Create role** +2. Choose **AWS Lambda** as the trusted service +3. Attach these managed policies: + - `AWSLambdaBasicExecutionRole` (CloudWatch Logs) + - Create custom policy for S3 access: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:PutObject" + ], + "Resource": "arn:aws:s3:::your-bucket-name/*" + } + ] +} +``` + +4. Name the role (e.g., `LambdaPDFRole`) and create it + +### Step 2: Create S3 Bucket for PDFs + +1. Go to **AWS Console → S3 → Create bucket** +2. Enter bucket name (e.g., `pdf-generation-bucket`) +3. Use default settings and create +4. Note the bucket name; you'll reference it in Lambda code + +### Step 3: Create Lambda Function + +**Option A: Using AWS Toolkit in Visual Studio** + +1. Open **AWS Explorer** in Visual Studio +2. Right-click **Lambda** → **Create New AWS Lambda Function** +3. Select **.NET 8** runtime +4. Create function (e.g., `CreatePDFDocument`) +5. Choose `Empty Function` template + +**Option B: Using AWS Console** + +1. Go to **AWS Console → Lambda → Create function** +2. Function name: `CreatePDFDocument` +3. Runtime: **.NET 8** (x86_64) +4. Execution role: Select the role created in Step 1 +5. Create function + +### Step 4: Add NuGet Package + +In your Lambda project, add the Syncfusion PDF package: + +```bash +dotnet add package Syncfusion.Pdf.NET +``` + +### Step 5: Implement Lambda Function Handler + +Replace the default code with this PDF generation handler: + +```csharp +using Amazon.Lambda.Core; +using Amazon.S3; +using Amazon.S3.Model; +using Syncfusion.Pdf; +using Syncfusion.Pdf.Graphics; +using Syncfusion.Pdf.Grid; +using System.Collections.Generic; + +[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] + +namespace PDFGenerationLambda; + +public class Function +{ + private readonly IAmazonS3 _s3Client = new AmazonS3Client(); + private const string BucketName = "your-bucket-name"; // Replace with your bucket + + public async Task FunctionHandler(ILambdaContext context) + { + try + { + context.Logger.LogLine("PDF generation started."); + + // Register Syncfusion license + Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + + // Generate PDF + using (PdfDocument document = new PdfDocument()) + { + document.PageSettings.Size = PdfPageSize.A4; + PdfPage page = document.Pages.Add(); + PdfGraphics graphics = page.Graphics; + + // Draw header + PdfStandardFont titleFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 20, PdfFontStyle.Bold); + graphics.DrawString("Adventure Works Cycles", titleFont, PdfBrushes.Black, new PointF(150, 50)); + + // Draw description + string text = "Adventure Works Cycles is a multinational manufacturing company that produces bicycles for commercial markets."; + PdfTextElement textElement = new PdfTextElement(text, new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); + textElement.Draw(page, new RectangleF(0, 100, page.GetClientSize().Width, page.GetClientSize().Height)); + + // Create product table + List productData = new List + { + new { Product_ID = "1001", Product_Name = "Bicycle", Price = "$10,000" }, + new { Product_ID = "1002", Product_Name = "Head Light", Price = "$3,000" }, + new { Product_ID = "1003", Product_Name = "Brake Wire", Price = "$1,500" }, + new { Product_ID = "1004", Product_Name = "Pedal Set", Price = "$2,000" }, + new { Product_ID = "1005", Product_Name = "Chain", Price = "$500" } + }; + + PdfGrid grid = new PdfGrid(); + grid.DataSource = productData; + grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); + grid.Draw(graphics, new RectangleF(0, 200, page.Size.Width - 80, 0)); + + // Save to S3 + using (MemoryStream stream = new MemoryStream()) + { + document.Save(stream); + stream.Position = 0; + + string fileName = $"AdventureWorks_{DateTime.UtcNow:yyyyMMdd_HHmmss}.pdf"; + + var putRequest = new PutObjectRequest + { + BucketName = BucketName, + Key = fileName, + InputStream = stream, + ContentType = "application/pdf" + }; + + await _s3Client.PutObjectAsync(putRequest); + context.Logger.LogLine($"PDF saved to S3: s3://{BucketName}/{fileName}"); + + return $"PDF generated successfully: {fileName}"; + } + } + } + catch (Exception ex) + { + context.Logger.LogLine($"Error generating PDF: {ex.Message}\n{ex.StackTrace}"); + throw; + } + } +} +``` + +### Step 6: Deploy Lambda Function + +**Using AWS Toolkit in Visual Studio:** + +1. Right-click project → **Publish to AWS Lambda** +2. Select function name created in Step 3 +3. Select IAM role from Step 1 +4. Click **Upload** + +**Using AWS CLI:** + +```bash +# Build release package +dotnet publish -c Release + +# Package for Lambda +cd bin/Release/net8.0/publish +zip -r ../function.zip . + +# Deploy (requires AWS CLI configured) +aws lambda update-function-code \ + --function-name CreatePDFDocument \ + --zip-file fileb://../function.zip +``` + +### Step 7: Test Lambda Function + +1. Go to **AWS Lambda → CreatePDFDocument → Test** +2. Create a test event (empty event: `{}`) +3. Click **Test** +4. View execution result in CloudWatch logs + +Verify the PDF was created in your S3 bucket: +- AWS Console → S3 → your-bucket-name → Check for new PDF files + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| **License Key Not Registered** | Ensure `SyncfusionLicenseProvider.RegisterLicense()` is called at Lambda handler startup. License must be registered before creating PdfDocument instances. | +| **Syncfusion.Pdf.NET Package Not Found** | Run `dotnet add package Syncfusion.Pdf.NET` or manually add to `.csproj`. Verify package version is v16.2.0.x or later for .NET 6.0+ support. | +| **"Access Denied" Uploading to S3** | Verify Lambda execution role has S3 PutObject permission. Check IAM policy includes correct S3 bucket ARN. | +| **Lambda Timeout (15 minutes max)** | Large PDF generation can exceed timeout. Optimize images, reduce content, or split into multiple functions. Monitor duration in CloudWatch. | +| **"No such file or directory" Error** | Lambda runtime is Linux-based. Use forward slashes in file paths: `/tmp/file.pdf` (not `\tmp\file.pdf`). | +| **Licensing Error in Production** | License key scope may differ between development and Lambda environments. Contact Syncfusion Support for serverless/Lambda licensing guidance. | +| **Memory Issues (128MB-10GB configurable)** | Increase Lambda memory allocation in Function Configuration. More memory = faster CPU = faster PDF generation. | +| **"Cannot find namespace" Compilation Error** | Ensure all NuGet dependencies are included. Run `dotnet restore` before building. Check `.csproj` for correct package references. | +| **S3 Bucket Name Not Found** | Verify BucketName variable in code matches actual S3 bucket name exactly (case-sensitive). Bucket must exist in same AWS region as Lambda. | +| **CloudWatch Logs Not Visible** | Verify Lambda execution role has `CloudWatchLogsFullAccess` or `AWSLambdaBasicExecutionRole` attached. Logs appear in CloudWatch after function execution. | + +## Next Steps + +Explore advanced PDF capabilities and AWS integration patterns: + +### Advanced PDF Features +- **[Merge Multiple PDFs](https://help.syncfusion.com/file-formats/pdf/working-with-documents/merge-documents)** — Combine reports from multiple Lambda invocations +- **[Split PDF Documents](https://help.syncfusion.com/file-formats/pdf/split-document)** — Extract pages based on S3 event triggers +- **[Add Watermarks](https://help.syncfusion.com/file-formats/pdf/working-with-pages/add-watermark)** — Add branding to generated PDFs +- **[Create Interactive Forms](https://help.syncfusion.com/file-formats/pdf/working-with-forms/overview)** — Build fillable PDF forms for data collection +- **[Digital Signatures](https://help.syncfusion.com/file-formats/pdf/working-with-forms/create-digital-signatures)** — Sign PDFs for compliance + +### AWS Integration Patterns +- **[S3 Event-Triggered Lambda](https://docs.aws.amazon.com/lambda/latest/dg/with-s3.html)** — Generate PDFs automatically when files are uploaded +- **[API Gateway + Lambda](https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html)** — Create REST API endpoints for on-demand PDF generation +- **[Lambda Layers for Code Sharing](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)** — Share common PDF logic across multiple functions +- **[Store Secrets Securely](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)** — Use AWS Secrets Manager for license keys (not hardcoded) +- **[Monitor with CloudWatch](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-cloudwatchlogs.html)** — Track PDF generation metrics and errors + +### Cost Optimization +- **[Lambda Provisioned Concurrency](https://docs.aws.amazon.com/lambda/latest/dg/provisioned-concurrency.html)** — Keep functions warm for consistent performance +- **[S3 Lifecycle Policies](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html)** — Archive old PDFs to reduce storage costs +- **[AWS Pricing Calculator](https://calculator.aws/)** — Estimate costs for your PDF generation workload + +## Resources + +**Sample Code:** +- [Complete Lambda PDF Generation Sample](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/AWS/Lambda) + +**Documentation:** +- [Syncfusion .NET PDF Library Guide](https://help.syncfusion.com/file-formats/pdf/) +- [AWS Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/) +- [AWS Lambda with .NET](https://docs.aws.amazon.com/lambda/latest/dg/lambda-dotnet.html) +- [Amazon S3 Documentation](https://docs.aws.amazon.com/s3/) +- [AWS Toolkit for Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/) + +**Try It Out:** +- [Syncfusion PDF Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) +- [AWS Free Tier](https://aws.amazon.com/free/) — Includes Lambda and S3 free usage tier +- [Explore Syncfusion PDF Features](https://www.syncfusion.com/document-sdk/net-pdf-library) diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-C-Sharp-VB-NET.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-C-Sharp-VB-NET.md index 5411eadd2e..205828ac1b 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-C-Sharp-VB-NET.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-C-Sharp-VB-NET.md @@ -5,20 +5,113 @@ description: Learn how to create or generate a PDF file in C# and VB.NET with el platform: document-processing control: PDF documentation: UG -keywords: create pdf, edit pdf, write pdf, merge, pdf form, fill form, digital sign, table, c#, vb.net, dotnet pdf +keywords: create pdf, edit pdf, write pdf, merge, pdf form, fill form, digital sign, table, c#, vb.net, dotnet pdf, syncfusion.pdf.net --- # Create or Generate PDF file in C# and VB.NET -The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) used to create PDF document from scratch and saving it to disk or stream. This library also offers functionality to merge, split, stamp, forms, and secure PDF files. +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create PDF documents from scratch with text, images, and tables, as well as manipulate existing PDFs. This library also offers functionality to merge, split, stamp, create forms, and secure PDF files. -To include the .NET PDF library into your application, please refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. +## Prerequisites + +| Requirement | Details | +|-------------|---------| +| **IDE** | Visual Studio 2019 or later (VS 2022 recommended) | +| **.NET Versions** | .NET Framework 4.5+, .NET 5.0+, .NET 6.0+, .NET 7.0, .NET 8.0 | +| **NuGet Package** | Syncfusion.Pdf.NET v16.2.0.x or later | +| **License Registration** | v16.2.0.x+ requires license registration for production use | +| **Optional Tools** | Visual Studio Code, Rider, or command-line interface (dotnet CLI) | +| **Community License** | Free license available from [Syncfusion Community License](https://help.syncfusion.com/common/essential-studio/licensing/community-license) | + +## Installing Syncfusion.Pdf.NET + +### NuGet Package Manager + +1. In Visual Studio, go to **Tools** → **NuGet Package Manager** → **Manage NuGet Packages for Solution** +2. Search for **Syncfusion.Pdf.NET** +3. Click **Install** and select the latest version (v16.2.0.x or later) + +### Command Line -N> 1. Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to know about registering Syncfusion® license key in your application to use our components. -N> 2. Unlike System.Drawing APIs all the units are measured in point instead of pixel. +```bash +dotnet add package Syncfusion.Pdf.NET +``` + +## Registering the License Key + +Starting with v16.2.0.x, the Syncfusion PDF library requires license registration. This ensures compliance and enables production deployments. + +**Step 1**: Register your license key at application startup. For ASP.NET Core, add the following to `Program.cs`: + +{% tabs %} +{% highlight c# tabtitle="C#" %} + +using Syncfusion.Licensing; + +var builder = WebApplication.CreateBuilder(args); +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); +builder.Services.AddControllers(); +var app = builder.Build(); +app.MapControllers(); +app.Run(); + +{% endhighlight %} +{% endtabs %} + +**Step 2**: For console applications, call the license registration method before creating your first PDF document: + +{% tabs %} +{% highlight c# tabtitle="C#" %} + +using Syncfusion.Licensing; +using Syncfusion.Pdf; + +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + +// Your PDF creation code here +PdfDocument document = new PdfDocument(); + +{% endhighlight %} + +{% highlight vb.net tabtitle="VB.NET" %} + +Imports Syncfusion.Licensing +Imports Syncfusion.Pdf + +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY") + +' Your PDF creation code here +Dim document As New PdfDocument() + +{% endhighlight %} +{% endtabs %} + +> **Security Note**: Never hardcode license keys in production code. Use environment variables or secure configuration management (Azure Key Vault, AWS Secrets Manager, etc.). Refer to [Licensing Overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) for production deployment guidance. + +## Supported Platforms + +The Syncfusion .NET PDF library works seamlessly across multiple platforms: +- **Windows**: Windows Forms, WPF, ASP.NET MVC, ASP.NET Core, UWP, Xamarin +- **Web**: ASP.NET MVC, ASP.NET Core, Blazor, Azure Functions, AWS Lambda +- **Cloud**: Azure App Service, Google App Engine, AWS Elastic Beanstalk +- **Cross-platform**: .NET 5.0+, .NET 6.0+, .NET 7.0, .NET 8.0 on Windows, Linux, and macOS + +> **Note**: Units are measured in **points** (not pixels) in the PDF library, similar to other PDF rendering engines. 1 inch = 72 points. + +To include the .NET PDF library into your application, please refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. To quickly get started with creating a PDF document in .NET, watch this video: {% youtube "https://www.youtube.com/watch?v=PvUdu1hpRLQ" %} +## Core Concepts + +Before diving into code examples, understand these important concepts: + +1. **PdfDocument**: Represents the entire PDF document being created. All pages and content are added to this object. +2. **PdfPage**: Represents a single page in the PDF document. Multiple pages can be added to a document. +3. **PdfGraphics**: Provides 2D drawing capabilities similar to GDI+ in Windows Forms. Used to draw text, images, and shapes. +4. **Resource Disposal**: Always use `using` statements with PDF objects to ensure proper resource disposal and prevent memory leaks in production environments. +5. **Cross-platform vs Windows-specific**: Use `Syncfusion.Drawing` for cross-platform .NET; use `System.Drawing` for Windows-only applications. + ## Creating a PDF document with simple text The following code example shows how to create a PDF document with simple text using the [DrawString](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawString_System_String_Syncfusion_Pdf_Graphics_PdfFont_Syncfusion_Pdf_Graphics_PdfBrush_System_Drawing_PointF_) method of the [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html) object to draw the text on the PDF page. @@ -30,20 +123,33 @@ using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; -//Create a new PDF document. -PdfDocument document = new PdfDocument(); -//Add a page to the document. -PdfPage page = document.Pages.Add(); -//Create PDF graphics for the page. -PdfGraphics graphics = page.Graphics; -//Set the standard font. -PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); -//Draw the text. -graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); -//Save the document. -document.Save("Output.pdf"); -//Close the document. -document.Close(true); +try +{ + // Create a new PDF document + using (PdfDocument document = new PdfDocument()) + { + // Add a page to the document + PdfPage page = document.Pages.Add(); + + // Create PDF graphics for the page + PdfGraphics graphics = page.Graphics; + + // Set the standard font + PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); + + // Draw the text + graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); + + // Save the document + document.Save("Output.pdf"); + } + + Console.WriteLine("PDF created successfully as Output.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error creating PDF: {ex.Message}"); +} {% endhighlight %} @@ -53,20 +159,33 @@ using System.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; -//Create a new PDF document. -PdfDocument document = new PdfDocument(); -//Add a page to the document. -PdfPage page = document.Pages.Add(); -//Create PDF graphics for the page. -PdfGraphics graphics = page.Graphics; -//Set the standard font. -PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); -//Draw the text. -graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); -//Save the document. -document.Save("Output.pdf"); -//Close the document. -document.Close(true); +try +{ + // Create a new PDF document + using (PdfDocument document = new PdfDocument()) + { + // Add a page to the document + PdfPage page = document.Pages.Add(); + + // Create PDF graphics for the page + PdfGraphics graphics = page.Graphics; + + // Set the standard font + PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); + + // Draw the text + graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); + + // Save the document + document.Save("Output.pdf"); + } + + Console.WriteLine("PDF created successfully as Output.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error creating PDF: {ex.Message}"); +} {% endhighlight %} @@ -76,103 +195,187 @@ Imports System.Drawing Imports Syncfusion.Pdf Imports Syncfusion.Pdf.Graphics -'Create a new PDF document. -Dim document As New PdfDocument() -'Add a page to the document. -Dim page As PdfPage = document.Pages.Add() -'Create PDF graphics for the page. -Dim graphics As PdfGraphics = page.Graphics -'Set the standard font. -Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20) -'Draw the text. -graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, New PointF(0, 0)) -'Save the document. -document.Save("Output.pdf") -'Close the document. -document.Close(True) +Try + ' Create a new PDF document + Using document As New PdfDocument() + ' Add a page to the document + Dim page As PdfPage = document.Pages.Add() + + ' Create PDF graphics for the page + Dim graphics As PdfGraphics = page.Graphics + + ' Set the standard font + Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20) + + ' Draw the text + graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, New PointF(0, 0)) + + ' Save the document + document.Save("Output.pdf") + End Using + + Console.WriteLine("PDF created successfully as Output.pdf") +Catch ex As Exception + Console.WriteLine($"Error creating PDF: {ex.Message}") +End Try {% endhighlight %} {% endtabs %} +### Expected Output + +The code above creates a simple PDF file named `Output.pdf` containing: +- Single page with default letter size (8.5" x 11") +- Text "Hello World!!!" in Helvetica font, 20 points, black color +- Text positioned at coordinates (0, 0) — top-left of page +- File size: approximately 2-3 KB + You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/blob/master/Getting%20Started/.NET/Create_PDF_NET/Create_PDF_NET/Program.cs). ## Creating a PDF document with image -The following code example shows how to generate a PDF document with an image using the [DrawImage](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawImage_Syncfusion_Pdf_Graphics_PdfImage_System_Single_System_Single_) method of the [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html) class. +The following code example shows how to generate a PDF document with an image using the [DrawImage](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawImage_Syncfusion_Pdf_Graphics_PdfImage_System_Single_System_Single_) method of the [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html) class. + +> **Note**: Ensure the image file (Autumn Leaves.jpg) exists in the application's working directory or provide the full path. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" %} using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; +using System; + +try +{ + using (PdfDocument doc = new PdfDocument()) + { + // Add a page to the document + PdfPage page = doc.Pages.Add(); + + // Create PDF graphics for the page + PdfGraphics graphics = page.Graphics; + + // Load the image as stream + string imagePath = "Autumn Leaves.jpg"; + if (!System.IO.File.Exists(imagePath)) + { + throw new System.IO.FileNotFoundException($"Image file not found: {imagePath}"); + } + + using (FileStream imageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) + { + PdfBitmap image = new PdfBitmap(imageStream); + + // Draw the image at position (0, 0) + graphics.DrawImage(image, 0, 0); + } + + // Save the document + doc.Save("Output.pdf"); + } + + Console.WriteLine("PDF with image created successfully as Output.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error creating PDF: {ex.Message}"); +} -//Create a new PDF document. -PdfDocument doc = new PdfDocument(); -//Add a page to the document. -PdfPage page = doc.Pages.Add(); -//Create PDF graphics for the page -PdfGraphics graphics = page.Graphics; -//Load the image as stream. -FileStream imageStream = new FileStream("Autumn Leaves.jpg", FileMode.Open, FileAccess.Read); -PdfBitmap image = new PdfBitmap(imageStream); -//Draw the image -graphics.DrawImage(image, 0, 0); -//Save the document. -doc.Save("Output.pdf"); -//Close the document. -doc.Close(true); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; +using System; + +try +{ + using (PdfDocument doc = new PdfDocument()) + { + // Add a page to the document + PdfPage page = doc.Pages.Add(); + + // Create PDF graphics for the page + PdfGraphics graphics = page.Graphics; + + // Load the image from disk + string imagePath = "Autumn Leaves.jpg"; + if (!System.IO.File.Exists(imagePath)) + { + throw new System.IO.FileNotFoundException($"Image file not found: {imagePath}"); + } + + PdfBitmap image = new PdfBitmap(imagePath); + + // Draw the image at position (0, 0) + graphics.DrawImage(image, 0, 0); + + // Save the document + doc.Save("Output.pdf"); + } + + Console.WriteLine("PDF with image created successfully as Output.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error creating PDF: {ex.Message}"); +} -//Create a new PDF document. -PdfDocument doc = new PdfDocument(); -//Add a page to the document. -PdfPage page = doc.Pages.Add(); -//Create PDF graphics for the page -PdfGraphics graphics = page.Graphics; -//Load the image from the disk. -PdfBitmap image = new PdfBitmap("Autumn Leaves.jpg"); -//Draw the image -graphics.DrawImage(image, 0, 0); -//Save the document. -doc.Save("Output.pdf"); -//Close the document. -doc.Close(true); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} Imports Syncfusion.Pdf Imports Syncfusion.Pdf.Graphics +Imports System + +Try + Using doc As New PdfDocument() + ' Add a page to the document + Dim page As PdfPage = doc.Pages.Add() + + ' Create PDF graphics for the page + Dim graphics As PdfGraphics = page.Graphics + + ' Load the image from disk + Dim imagePath As String = "Autumn Leaves.jpg" + If Not System.IO.File.Exists(imagePath) Then + Throw New System.IO.FileNotFoundException($"Image file not found: {imagePath}") + End If + + Dim image As New PdfBitmap(imagePath) + + ' Draw the image at position (0, 0) + graphics.DrawImage(image, 0, 0) + + ' Save the document + doc.Save("Output.pdf") + End Using + + Console.WriteLine("PDF with image created successfully as Output.pdf") +Catch ex As Exception + Console.WriteLine($"Error creating PDF: {ex.Message}") +End Try -'Create a new PDF document. -Dim doc As New PdfDocument() -'Add a page to the document. -Dim page As PdfPage = doc.Pages.Add() -'Create PDF graphics for the page -Dim graphics As PdfGraphics = page.Graphics -'Load the image from the disk. -Dim image As New PdfBitmap("Autumn Leaves.jpg") -'Draw the image -graphics.DrawImage(image, 0, 0) -'Save the document. -doc.Save("Output.pdf") -'Close the document. -doc.Close(True) {% endhighlight %} {% endtabs %} +### Expected Output + +The code above creates a PDF file named `Output.pdf` containing: +- Single page with the image (Autumn Leaves.jpg) embedded +- Image positioned at top-left corner (0, 0) +- Image dimensions: original size or scaled based on PdfBitmap parameters +- File size: depends on image compression (typically 50-200 KB for photos) + You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/.NET/Create_PDF_with_image_NET). ## Creating a PDF document with table -The following code example shows how to generate a PDF document with a simple table from a [DataSource](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Grid.PdfGrid.html#Syncfusion_Pdf_Grid_PdfGrid_DataSource) using the [PdfGrid](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Grid.PdfGrid.html) class. The [DataSource](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Grid.PdfGrid.html#Syncfusion_Pdf_Grid_PdfGrid_DataSource) can be a data set, data table, arrays or an IEnumerable object. +The following code example shows how to generate a PDF document with a simple table from a [DataSource](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Grid.PdfGrid.html#Syncfusion_Pdf_Grid_PdfGrid_DataSource) using the [PdfGrid](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Grid.PdfGrid.html) class. The [DataSource](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Grid.PdfGrid.html#Syncfusion_Pdf_Grid_PdfGrid_DataSource) can be a data set, data table, arrays, or an IEnumerable object. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" %} @@ -181,34 +384,48 @@ using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Grid; using System.Data; +using System; -//Create a new PDF document -PdfDocument doc = new PdfDocument(); -//Add a page -PdfPage page = doc.Pages.Add(); -//Create a PdfGrid -PdfGrid pdfGrid = new PdfGrid(); -//Create a DataTable -DataTable dataTable = new DataTable(); -//Add columns to the DataTable -dataTable.Columns.Add("ProductID"); -dataTable.Columns.Add("ProductName"); -dataTable.Columns.Add("Quantity"); -dataTable.Columns.Add("UnitPrice"); -dataTable.Columns.Add("Discount"); -dataTable.Columns.Add("Price"); -//Add rows to the DataTable -dataTable.Rows.Add(new object[] { "CA-1098", "Queso Cabrales", "12", "14", "1", "167" }); -dataTable.Rows.Add(new object[] { "LJ-0192-M", "Singaporean Hokkien Fried Mee", "10", "20", "3", "197" }); -dataTable.Rows.Add(new object[] { "SO-B909-M", "Mozzarella di Giovanni", "15", "65", "10", "956"}); -//Assign data source -pdfGrid.DataSource = dataTable; -//Draw grid to the page of PDF document -pdfGrid.Draw(page, new PointF(10, 10)); -//Save the document -doc.Save("Output.pdf"); -//Close the document -doc.Close(true); +try +{ + using (PdfDocument doc = new PdfDocument()) + { + // Add a page + PdfPage page = doc.Pages.Add(); + + // Create a PdfGrid + PdfGrid pdfGrid = new PdfGrid(); + + // Create a DataTable with sample product data + DataTable dataTable = new DataTable(); + dataTable.Columns.Add("ProductID"); + dataTable.Columns.Add("ProductName"); + dataTable.Columns.Add("Quantity"); + dataTable.Columns.Add("UnitPrice"); + dataTable.Columns.Add("Discount"); + dataTable.Columns.Add("Price"); + + // Add sample rows + dataTable.Rows.Add(new object[] { "CA-1098", "Queso Cabrales", "12", "14", "1", "167" }); + dataTable.Rows.Add(new object[] { "LJ-0192-M", "Singaporean Hokkien Fried Mee", "10", "20", "3", "197" }); + dataTable.Rows.Add(new object[] { "SO-B909-M", "Mozzarella di Giovanni", "15", "65", "10", "956" }); + + // Assign data source to grid + pdfGrid.DataSource = dataTable; + + // Draw grid to the page at position (10, 10) + pdfGrid.Draw(page, new PointF(10, 10)); + + // Save the document + doc.Save("Output.pdf"); + } + + Console.WriteLine("PDF with table created successfully as Output.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error creating PDF: {ex.Message}"); +} {% endhighlight %} @@ -218,76 +435,109 @@ using System.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Grid; using System.Data; +using System; -//Create a new PDF document -PdfDocument doc = new PdfDocument(); -//Add a page -PdfPage page = doc.Pages.Add(); -//Create a PdfGrid -PdfGrid pdfGrid = new PdfGrid(); -//Create a DataTable -DataTable dataTable = new DataTable(); -//Add columns to the DataTable -dataTable.Columns.Add("ProductID"); -dataTable.Columns.Add("ProductName"); -dataTable.Columns.Add("Quantity"); -dataTable.Columns.Add("UnitPrice"); -dataTable.Columns.Add("Discount"); -dataTable.Columns.Add("Price"); -//Add rows to the DataTable -dataTable.Rows.Add(new object[] { "CA-1098", "Queso Cabrales", "12", "14", "1", "167" }); -dataTable.Rows.Add(new object[] { "LJ-0192-M", "Singaporean Hokkien Fried Mee", "10", "20", "3", "197" }); -dataTable.Rows.Add(new object[] { "SO-B909-M", "Mozzarella di Giovanni", "15", "65", "10", "956"}); -//Assign data source -pdfGrid.DataSource = dataTable; -//Draw grid to the page of PDF document -pdfGrid.Draw(page, new PointF(10, 10)); -//Save the document -doc.Save("Output.pdf"); -//Close the document -doc.Close(true); +try +{ + using (PdfDocument doc = new PdfDocument()) + { + // Add a page + PdfPage page = doc.Pages.Add(); + + // Create a PdfGrid + PdfGrid pdfGrid = new PdfGrid(); + + // Create a DataTable with sample product data + DataTable dataTable = new DataTable(); + dataTable.Columns.Add("ProductID"); + dataTable.Columns.Add("ProductName"); + dataTable.Columns.Add("Quantity"); + dataTable.Columns.Add("UnitPrice"); + dataTable.Columns.Add("Discount"); + dataTable.Columns.Add("Price"); + + // Add sample rows + dataTable.Rows.Add(new object[] { "CA-1098", "Queso Cabrales", "12", "14", "1", "167" }); + dataTable.Rows.Add(new object[] { "LJ-0192-M", "Singaporean Hokkien Fried Mee", "10", "20", "3", "197" }); + dataTable.Rows.Add(new object[] { "SO-B909-M", "Mozzarella di Giovanni", "15", "65", "10", "956" }); + + // Assign data source to grid + pdfGrid.DataSource = dataTable; + + // Draw grid to the page at position (10, 10) + pdfGrid.Draw(page, new PointF(10, 10)); + + // Save the document + doc.Save("Output.pdf"); + } + + Console.WriteLine("PDF with table created successfully as Output.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error creating PDF: {ex.Message}"); +} {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -Imports Syncfusion.Drawing +Imports System.Drawing Imports Syncfusion.Pdf Imports Syncfusion.Pdf.Grid Imports System.Data - -'Create a new PDF document. -Dim doc As New PdfDocument() -'Add a page. -Dim page As PdfPage = doc.Pages.Add() -'Create a PdfGrid. -Dim pdfGrid As New PdfGrid() -'Create a DataTable. -Dim dataTable As New DataTable() -'Add columns to the DataTable -dataTable.Columns.Add("ProductID") -dataTable.Columns.Add("ProductName") -dataTable.Columns.Add("Quantity") -dataTable.Columns.Add("UnitPrice") -dataTable.Columns.Add("Discount") -dataTable.Columns.Add("Price") -'Add rows to the DataTable -dataTable.Rows.Add(New Object() {"CA-1098", "Queso Cabrales", "12", "14", "1", "167"}) -dataTable.Rows.Add(New Object() {"LJ-0192-M", "Singaporean Hokkien Fried Mee", "10", "20", "3", "197"}) -dataTable.Rows.Add(New Object() {"SO-B909-M", "Mozzarella di Giovanni", "15", "65", "10", "956"}) -'Assign data source -pdfGrid.DataSource = dataTable -'Draw grid to the page of PDF document -pdfGrid.Draw(page, New PointF(10, 10)) -'Save the document -doc.Save("Output.pdf") -'Close the document -doc.Close(true) +Imports System + +Try + Using doc As New PdfDocument() + ' Add a page + Dim page As PdfPage = doc.Pages.Add() + + ' Create a PdfGrid + Dim pdfGrid As New PdfGrid() + + ' Create a DataTable with sample product data + Dim dataTable As New DataTable() + dataTable.Columns.Add("ProductID") + dataTable.Columns.Add("ProductName") + dataTable.Columns.Add("Quantity") + dataTable.Columns.Add("UnitPrice") + dataTable.Columns.Add("Discount") + dataTable.Columns.Add("Price") + + ' Add sample rows + dataTable.Rows.Add(New Object() {"CA-1098", "Queso Cabrales", "12", "14", "1", "167"}) + dataTable.Rows.Add(New Object() {"LJ-0192-M", "Singaporean Hokkien Fried Mee", "10", "20", "3", "197"}) + dataTable.Rows.Add(New Object() {"SO-B909-M", "Mozzarella di Giovanni", "15", "65", "10", "956"}) + + ' Assign data source to grid + pdfGrid.DataSource = dataTable + + ' Draw grid to the page at position (10, 10) + pdfGrid.Draw(page, New PointF(10, 10)) + + ' Save the document + doc.Save("Output.pdf") + End Using + + Console.WriteLine("PDF with table created successfully as Output.pdf") +Catch ex As Exception + Console.WriteLine($"Error creating PDF: {ex.Message}") +End Try {% endhighlight %} {% endtabs %} +### Expected Output + +The code above creates a PDF file named `Output.pdf` containing: +- Single page with a formatted table +- 6 columns: ProductID, ProductName, Quantity, UnitPrice, Discount, Price +- 3 rows of product data +- Table positioned 10 points from left and top margins +- File size: approximately 5-10 KB + You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/.NET/Create_PDF_with_table_NET). ## Creating a simple PDF document with basic elements @@ -663,99 +913,195 @@ You can download a complete working sample from [GitHub](https://github.com/Sync The following screenshot shows the invoice PDF document created by using .NET PDF library. ![PDF invoice output](GettingStarted_images/pdf-invoice.png) -## Filling forms +## Filling Interactive Forms (AcroForms) -An interactive form, sometimes referred to as an AcroForm is a collection of fields for gathering information interactively from the user. A [PDF document](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) or an [existing PDF document](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Parsing.PdfLoadedDocument.html) can contain any number of fields appearing in any combination of pages, all of that make a single, globally interactive form spanning the entire document. +Interactive forms, also called AcroForms, are collections of fields for gathering information interactively from users. A [PDF document](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) or [existing PDF document](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Parsing.PdfLoadedDocument.html) can contain any number of fields across multiple pages, creating a globally interactive form spanning the entire document. -.NET PDF library allows you to [create/write and manipulate existing form](https://www.syncfusion.com/document-processing/pdf-framework/net/pdf-library/pdf-form-fields) in PDF document using the [PdfForm](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Interactive.PdfForm.html) class. To work with existing form documents, the following namespaces are required. +Syncfusion PDF library allows you to [create and manipulate form fields](https://www.syncfusion.com/document-processing/pdf-framework/net/pdf-library/pdf-form-fields) in PDF documents using the [PdfForm](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Interactive.PdfForm.html) class. -1. Syncfusion.Pdf -2. Syncfusion.Pdf.Parsing +**Required Namespaces:** +- `Syncfusion.Pdf` +- `Syncfusion.Pdf.Parsing` +- `Syncfusion.Pdf.Interactive` The following guide shows how to fill a sample PDF form programmatically. + ![Sample PDF form](GettingStarted_images/fill-pdf-forms.png) -.NET PDF library allows you to fill the form fields by using [PdfLoadedField](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Parsing.PdfLoadedField.html) class. You can get the form field either by using its field name or field index. +Syncfusion PDF library allows you to fill form fields using the [PdfLoadedField](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Parsing.PdfLoadedField.html) class. You can access form fields either by field name or field index. + +**Note**: You will need an existing PDF form (such as JobApplication.pdf). Refer to [PDF Form Fields Documentation](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/working-with-forms) to learn how to create PDF forms, or download a sample form from the Syncfusion examples repository. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" %} using Syncfusion.Pdf.Parsing; +using System; -//Loads the PDF form. -PdfLoadedDocument loadedDocument = new PdfLoadedDocument(@"JobApplication.pdf"); -//Loads the form -PdfLoadedForm form = loadedDocument.Form; -//Fills the textbox field by using index -(form.Fields[0] as PdfLoadedTextBoxField).Text = "John"; -//Fills the textbox fields by using field name -(form.Fields["LastName"] as PdfLoadedTextBoxField).Text = "Doe"; -(form.Fields["Address"] as PdfLoadedTextBoxField).Text = " John Doe \n 123 Main St \n Any town, USA"; -//Loads the radio button group -PdfLoadedRadioButtonItemCollection radioButtonCollection = (form.Fields["Gender"] as PdfLoadedRadioButtonListField).Items; -//Checks the 'Male' option -radioButtonCollection[0].Checked = true; -//Checks the 'business' checkbox field -(form.Fields["Business"] as PdfLoadedCheckBoxField).Checked = true; -//Checks the 'retiree' checkbox field -(form.Fields["Retiree"] as PdfLoadedCheckBoxField).Checked = true; -//Saves and closes the document -loadedDocument.Save("output.pdf"); -loadedDocument.Close(true); +try +{ + string formPath = "JobApplication.pdf"; + + // Verify the form file exists + if (!System.IO.File.Exists(formPath)) + { + throw new System.IO.FileNotFoundException($"Form PDF not found: {formPath}"); + } + + // Load the PDF form + using (PdfLoadedDocument loadedDocument = new PdfLoadedDocument(formPath)) + { + // Access the form + PdfLoadedForm form = loadedDocument.Form; + + if (form == null || form.Fields.Count == 0) + { + throw new InvalidOperationException("PDF document does not contain form fields"); + } + + // Fill textbox field by index + if (form.Fields.Count > 0) + { + (form.Fields[0] as PdfLoadedTextBoxField).Text = "John"; + } + + // Fill textbox fields by name + (form.Fields["LastName"] as PdfLoadedTextBoxField).Text = "Doe"; + (form.Fields["Address"] as PdfLoadedTextBoxField).Text = "John Doe\n123 Main St\nAnytown, USA"; + + // Set radio button selection + PdfLoadedRadioButtonItemCollection radioButtonCollection = (form.Fields["Gender"] as PdfLoadedRadioButtonListField)?.Items; + if (radioButtonCollection != null && radioButtonCollection.Count > 0) + { + radioButtonCollection[0].Checked = true; + } + + // Check checkbox fields + (form.Fields["Business"] as PdfLoadedCheckBoxField).Checked = true; + (form.Fields["Retiree"] as PdfLoadedCheckBoxField).Checked = true; + + // Save the filled form + loadedDocument.Save("FilledForm.pdf"); + } + + Console.WriteLine("Form filled successfully as FilledForm.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error filling form: {ex.Message}"); +} {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} using Syncfusion.Pdf.Parsing; +using System; -//Loads the PDF form. -PdfLoadedDocument loadedDocument = new PdfLoadedDocument(@"JobApplication.pdf"); -//Loads the form -PdfLoadedForm form = loadedDocument.Form; -//Fills the textbox field by using index -(form.Fields[0] as PdfLoadedTextBoxField).Text = "John"; -//Fills the textbox fields by using field name -(form.Fields["LastName"] as PdfLoadedTextBoxField).Text = "Doe"; -(form.Fields["Address"] as PdfLoadedTextBoxField).Text = " John Doe \n 123 Main St \n Any town, USA"; -//Loads the radio button group -PdfLoadedRadioButtonItemCollection radioButtonCollection = (form.Fields["Gender"] as PdfLoadedRadioButtonListField).Items; -//Checks the 'Male' option -radioButtonCollection[0].Checked = true; -//Checks the 'business' checkbox field -(form.Fields["Business"] as PdfLoadedCheckBoxField).Checked = true; -//Checks the 'retiree' checkbox field -(form.Fields["Retiree"] as PdfLoadedCheckBoxField).Checked = true; -//Saves and closes the document -loadedDocument.Save("output.pdf"); -loadedDocument.Close(true); +try +{ + string formPath = "JobApplication.pdf"; + + // Verify the form file exists + if (!System.IO.File.Exists(formPath)) + { + throw new System.IO.FileNotFoundException($"Form PDF not found: {formPath}"); + } + + // Load the PDF form + using (PdfLoadedDocument loadedDocument = new PdfLoadedDocument(formPath)) + { + // Access the form + PdfLoadedForm form = loadedDocument.Form; + + if (form == null || form.Fields.Count == 0) + { + throw new InvalidOperationException("PDF document does not contain form fields"); + } + + // Fill textbox field by index + if (form.Fields.Count > 0) + { + (form.Fields[0] as PdfLoadedTextBoxField).Text = "John"; + } + + // Fill textbox fields by name + (form.Fields["LastName"] as PdfLoadedTextBoxField).Text = "Doe"; + (form.Fields["Address"] as PdfLoadedTextBoxField).Text = "John Doe\n123 Main St\nAnytown, USA"; + + // Set radio button selection + PdfLoadedRadioButtonItemCollection radioButtonCollection = (form.Fields["Gender"] as PdfLoadedRadioButtonListField)?.Items; + if (radioButtonCollection != null && radioButtonCollection.Count > 0) + { + radioButtonCollection[0].Checked = true; + } + + // Check checkbox fields + (form.Fields["Business"] as PdfLoadedCheckBoxField).Checked = true; + (form.Fields["Retiree"] as PdfLoadedCheckBoxField).Checked = true; + + // Save the filled form + loadedDocument.Save("FilledForm.pdf"); + } + + Console.WriteLine("Form filled successfully as FilledForm.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error filling form: {ex.Message}"); +} {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} Imports Syncfusion.Pdf.Parsing - -'Loads the PDF form. -Dim loadedDocument As New PdfLoadedDocument("JobApplication.pdf") -'Load the form -Dim form As PdfLoadedForm = loadedDocument.Form -'Fills the textbox field by using index -TryCast(form.Fields(0), PdfLoadedTextBoxField).Text = "John" -'Fills the textbox fields by using field name -TryCast(form.Fields("LastName"), PdfLoadedTextBoxField).Text = "Doe" -TryCast(form.Fields("Address"), PdfLoadedTextBoxField).Text = " John Doe " & vbLf & " 123 Main St " & vbLf & " Any town, USA" -'Load the radio button group -Dim radioButtonCollection As PdfLoadedRadioButtonItemCollection = TryCast(form.Fields("Gender"), PdfLoadedRadioButtonListField).Items -'Checks the 'Male' option -radioButtonCollection(0).Checked = True -'Checks the 'business' checkbox field -TryCast(form.Fields("Business"), PdfLoadedCheckBoxField).Checked = True -'Checks the 'retiree' checkbox field -TryCast(form.Fields("Retiree"), PdfLoadedCheckBoxField).Checked = True -'Saves and closes the document -loadedDocument.Save("output.pdf") -loadedDocument.Close(True) +Imports System + +Try + Dim formPath As String = "JobApplication.pdf" + + ' Verify the form file exists + If Not System.IO.File.Exists(formPath) Then + Throw New System.IO.FileNotFoundException($"Form PDF not found: {formPath}") + End If + + ' Load the PDF form + Using loadedDocument As New PdfLoadedDocument(formPath) + ' Access the form + Dim form As PdfLoadedForm = loadedDocument.Form + + If form Is Nothing OrElse form.Fields.Count = 0 Then + Throw New InvalidOperationException("PDF document does not contain form fields") + End If + + ' Fill textbox field by index + If form.Fields.Count > 0 Then + TryCast(form.Fields(0), PdfLoadedTextBoxField).Text = "John" + End If + + ' Fill textbox fields by name + TryCast(form.Fields("LastName"), PdfLoadedTextBoxField).Text = "Doe" + TryCast(form.Fields("Address"), PdfLoadedTextBoxField).Text = "John Doe" & vbLf & "123 Main St" & vbLf & "Anytown, USA" + + ' Set radio button selection + Dim radioButtonCollection As PdfLoadedRadioButtonItemCollection = TryCast(form.Fields("Gender"), PdfLoadedRadioButtonListField)?.Items + If radioButtonCollection IsNot Nothing AndAlso radioButtonCollection.Count > 0 Then + radioButtonCollection(0).Checked = True + End If + + ' Check checkbox fields + TryCast(form.Fields("Business"), PdfLoadedCheckBoxField).Checked = True + TryCast(form.Fields("Retiree"), PdfLoadedCheckBoxField).Checked = True + + ' Save the filled form + loadedDocument.Save("FilledForm.pdf") + End Using + + Console.WriteLine("Form filled successfully as FilledForm.pdf") +Catch ex As Exception + Console.WriteLine($"Error filling form: {ex.Message}") +End Try {% endhighlight %} @@ -763,14 +1109,26 @@ loadedDocument.Close(True) You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/.NET/Filling_forms_NET). -The filled form is shown in adobe reader application as follows. +### Expected Output + +The code above creates a PDF file named `FilledForm.pdf` containing: +- All form fields populated with provided values +- First Name: "John" +- Last Name: "Doe" +- Address: Multi-line text +- Gender: "Male" radio button selected +- Checkboxes: "Business" and "Retiree" checked +- File size: approximately 20-50 KB depending on original form complexity + +The filled form displayed in Adobe Reader application: + ![Filled PDF form output](GettingStarted_images/filled-form-in-pdf.jpeg) -## Converting HTML files to PDF +## Converting HTML Files to PDF -The [HTML-to-PDF converter](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/converting-html-to-pdf) is a .NET library for converting webpages, SVG, MHTML, and HTML files to PDF using C#. It uses the popular rendering engine [Blink](https://en.wikipedia.org/wiki/Blink_(browser_engine)) (Google Chrome) and the result preserves all graphics, images, text, fonts, and the layout of the original HTML document or webpage. +The [HTML-to-PDF converter](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/converting-html-to-pdf) is a .NET library for converting webpages, SVG, MHTML, and HTML files to PDF using C#. It uses the popular rendering engine [Blink](https://en.wikipedia.org/wiki/Blink_(browser_engine)) (Google Chrome), preserving all graphics, images, text, fonts, and layout from the original HTML document or webpage. -The HTML-to-PDF converter works seamlessly in various platforms: [Azure App Services](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/convert-html-to-pdf-in-azure-app-service-linux), [Azure Functions](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/convert-html-to-pdf-in-azure-functions-linux), [AWS Lambda](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/convert-html-to-pdf-in-aws-lambda), [Docker](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/docker), [WinForms](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/windows-forms), [WPF](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/wpf), [Blazor](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/blazor), [ASP.NET MVC](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/aspnet-mvc), [ASP.NET Core](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/net-core) with [Windows](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/windows-forms), [Linux](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/linux), and [MacOS](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/mac). +The HTML-to-PDF converter works seamlessly across multiple platforms: [Azure App Services](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/convert-html-to-pdf-in-azure-app-service-linux), [Azure Functions](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/convert-html-to-pdf-in-azure-functions-linux), [AWS Lambda](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/convert-html-to-pdf-in-aws-lambda), [Docker](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/docker), [WinForms](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/windows-forms), [WPF](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/wpf), [Blazor](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/blazor), [ASP.NET MVC](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/aspnet-mvc), [ASP.NET Core](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/net-core) with [Windows](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/windows-forms), [Linux](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/linux), and [macOS](https://help.syncfusion.com/document-processing/pdf/conversions/html-to-pdf/net/mac). **Install HTML to PDF .NET library to your project** @@ -902,76 +1260,241 @@ document.Close(True) You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/.NET/HTML_string_to_PDF_NET). -## Merge PDF Documents +## Merging PDF Documents + +Syncfusion PDF library supports [merging multiple PDF documents](https://www.syncfusion.com/document-processing/pdf-framework/net/pdf-library/merge-pdf) from disk and stream using the [Merge](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocumentBase.html#Syncfusion_Pdf_PdfDocumentBase_Merge_Syncfusion_Pdf_PdfDocumentBase_Syncfusion_Pdf_Parsing_PdfLoadedDocument_) method of the [PdfDocumentBase](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocumentBase.html) class. You can merge multiple PDF documents from disk by specifying the paths in a string array. + +### Merging PDF Documents from Disk -Essential® PDF supports [merging multiple PDF documents](https://www.syncfusion.com/document-processing/pdf-framework/net/pdf-library/merge-pdf) from disk and stream using [Merge](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocumentBase.html#Syncfusion_Pdf_PdfDocumentBase_Merge_Syncfusion_Pdf_PdfDocumentBase_Syncfusion_Pdf_Parsing_PdfLoadedDocument_) method of the [PdfDocumentBase](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocumentBase.html) class. You can merge the multiple PDF documents from disk by specifying the path of the documents in a string array. +The following code example shows how to merge multiple PDF files from disk: -Refer to the following code example to merge multiple documents from disk. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" %} using Syncfusion.Pdf; +using System; -// Create the new PDF document -PdfDocument finalDoc = new PdfDocument(); -// Creates a string array of source files to be merged. -string[] source = { "file1.pdf, file2.pdf" }; -// Merges PDFDocument. -PdfDocument.Merge(finalDoc, source); -//Saves the final document -finalDoc.Save("Sample.pdf"); -//Closes the document -finalDoc.Close(true); +try +{ + // Create a destination document to hold merged content + using (PdfDocument finalDoc = new PdfDocument()) + { + // Create string array with source file paths (IMPORTANT: separate by comma in array) + string[] sourceFiles = { "file1.pdf", "file2.pdf", "file3.pdf" }; + + // Verify all files exist before merging + foreach (string file in sourceFiles) + { + if (!System.IO.File.Exists(file)) + { + throw new System.IO.FileNotFoundException($"Source PDF not found: {file}"); + } + } + + // Merge all PDF documents into the final document + PdfDocument.Merge(finalDoc, sourceFiles); + + // Save the merged document + finalDoc.Save("MergedOutput.pdf"); + } + + Console.WriteLine("PDFs merged successfully as MergedOutput.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error merging PDFs: {ex.Message}"); +} {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} using Syncfusion.Pdf; +using System; -// Create the new PDF document -PdfDocument finalDoc = new PdfDocument(); -// Creates a string array of source files to be merged. -string[] source = { "file1.pdf, file2.pdf" }; -// Merges PDFDocument. -PdfDocument.Merge(finalDoc, source); -//Saves the final document -finalDoc.Save("Sample.pdf"); -//Closes the document -finalDoc.Close(true); +try +{ + // Create a destination document to hold merged content + using (PdfDocument finalDoc = new PdfDocument()) + { + // Create string array with source file paths (IMPORTANT: separate by comma in array) + string[] sourceFiles = { "file1.pdf", "file2.pdf", "file3.pdf" }; + + // Verify all files exist before merging + foreach (string file in sourceFiles) + { + if (!System.IO.File.Exists(file)) + { + throw new System.IO.FileNotFoundException($"Source PDF not found: {file}"); + } + } + + // Merge all PDF documents into the final document + PdfDocument.Merge(finalDoc, sourceFiles); + + // Save the merged document + finalDoc.Save("MergedOutput.pdf"); + } + + Console.WriteLine("PDFs merged successfully as MergedOutput.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error merging PDFs: {ex.Message}"); +} {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} Imports Syncfusion.Pdf - -'Create the new PDF document -Dim finalDoc As New PdfDocument() -'Creates a string array of source files to be merged. -Dim source As String() = {"file1.pdf, file2.pdf"} -'Merges PDFDocument. -PdfDocument.Merge(finalDoc, source) -'Saves the final document -finalDoc.Save("Sample.pdf") -'Closes the document -finalDoc.Close(True) +Imports System + +Try + ' Create a destination document to hold merged content + Using finalDoc As New PdfDocument() + ' Create string array with source file paths (IMPORTANT: separate by comma in array) + Dim sourceFiles As String() = {"file1.pdf", "file2.pdf", "file3.pdf"} + + ' Verify all files exist before merging + For Each file In sourceFiles + If Not System.IO.File.Exists(file) Then + Throw New System.IO.FileNotFoundException($"Source PDF not found: {file}") + End If + Next + + ' Merge all PDF documents into the final document + PdfDocument.Merge(finalDoc, sourceFiles) + + ' Save the merged document + finalDoc.Save("MergedOutput.pdf") + End Using + + Console.WriteLine("PDFs merged successfully as MergedOutput.pdf") +Catch ex As Exception + Console.WriteLine($"Error merging PDFs: {ex.Message}") +End Try {% endhighlight %} {% endtabs %} -You can merge the [PDF document](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) streams by using the following code example. +> **Important**: When creating a string array, use `{ "file1.pdf", "file2.pdf" }` (separate files with commas). Do NOT use `{ "file1.pdf, file2.pdf" }` (which creates a single string with comma). + +### Merging PDF Document Streams + +The following code example shows how to merge PDF documents from streams: {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" %} using Syncfusion.Pdf; +using Syncfusion.Pdf.Parsing; +using System; -//Creates the destination document -PdfDocument finalDoc = new PdfDocument(); -Stream stream1 = File.OpenRead("file1.pdf"); -Stream stream2 = File.OpenRead("file2.pdf"); -//Creates a PDF stream for merging. +try +{ + // Create a destination document + using (PdfDocument finalDoc = new PdfDocument()) + { + // Open source PDF files as streams + using (Stream stream1 = System.IO.File.OpenRead("file1.pdf")) + using (Stream stream2 = System.IO.File.OpenRead("file2.pdf")) + { + // Load PDF documents from streams + using (PdfLoadedDocument sourceDoc1 = new PdfLoadedDocument(stream1)) + using (PdfLoadedDocument sourceDoc2 = new PdfLoadedDocument(stream2)) + { + // Merge source documents into final document + finalDoc.Merge(sourceDoc1); + finalDoc.Merge(sourceDoc2); + } + } + + // Save the merged document + finalDoc.Save("MergedOutput.pdf"); + } + + Console.WriteLine("PDFs merged from streams successfully as MergedOutput.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error merging PDFs: {ex.Message}"); +} + +{% endhighlight %} + +{% highlight c# tabtitle="C# [Windows-specific]" %} + +using Syncfusion.Pdf; +using Syncfusion.Pdf.Parsing; +using System; + +try +{ + // Create a destination document + using (PdfDocument finalDoc = new PdfDocument()) + { + // Open source PDF files as streams + using (Stream stream1 = System.IO.File.OpenRead("file1.pdf")) + using (Stream stream2 = System.IO.File.OpenRead("file2.pdf")) + { + // Load PDF documents from streams + using (PdfLoadedDocument sourceDoc1 = new PdfLoadedDocument(stream1)) + using (PdfLoadedDocument sourceDoc2 = new PdfLoadedDocument(stream2)) + { + // Merge source documents into final document + finalDoc.Merge(sourceDoc1); + finalDoc.Merge(sourceDoc2); + } + } + + // Save the merged document + finalDoc.Save("MergedOutput.pdf"); + } + + Console.WriteLine("PDFs merged from streams successfully as MergedOutput.pdf"); +} +catch (Exception ex) +{ + Console.WriteLine($"Error merging PDFs: {ex.Message}"); +} + +{% endhighlight %} + +{% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} + +Imports Syncfusion.Pdf +Imports Syncfusion.Pdf.Parsing +Imports System + +Try + ' Create a destination document + Using finalDoc As New PdfDocument() + ' Open source PDF files as streams + Using stream1 = System.IO.File.OpenRead("file1.pdf") + Using stream2 = System.IO.File.OpenRead("file2.pdf") + ' Load PDF documents from streams + Using sourceDoc1 As New PdfLoadedDocument(stream1) + Using sourceDoc2 As New PdfLoadedDocument(stream2) + ' Merge source documents into final document + finalDoc.Merge(sourceDoc1) + finalDoc.Merge(sourceDoc2) + End Using + End Using + End Using + End Using + + ' Save the merged document + finalDoc.Save("MergedOutput.pdf") + End Using + + Console.WriteLine("PDFs merged from streams successfully as MergedOutput.pdf") +Catch ex As Exception + Console.WriteLine($"Error merging PDFs: {ex.Message}") +End Try + +{% endhighlight %} +{% endtabs %} Stream[] streams = { stream1, stream2 }; //Merges PDFDocument. PdfDocumentBase.Merge(finalDoc, streams); diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Console.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Console.md index 6e4baeae1f..52b9a4f773 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Console.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Console.md @@ -1,19 +1,39 @@ --- -title: Create PDF file in Console Application | Syncfusion -description: Discover how to generate a PDF in a Console Application by using the Syncfusion PDF library efficiently. +title: Create a PDF File in Console Application | Syncfusion +description: Learn how to create PDF files in a Console Application using the Syncfusion .NET PDF library. platform: document-processing control: PDF documentation: UG --- -# Create or Generate a PDF file in a Console application +# Create a PDF File in a Console Application The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, work with forms, and secure PDF files. +## Prerequisites + +| Item | .NET Core / .NET 5.0+ | .NET Framework 4.5+ | +| --- | --- | --- | +| **Development Environment** | Visual Studio 2022, Visual Studio Code, JetBrains Rider | Visual Studio 2022, Visual Studio 2019 | +| **.NET Version** | .NET 5.0 or later (.NET 6.0+ recommended) | .NET Framework 4.5, 4.6, 4.7, 4.8 | +| **NuGet Package** | Syncfusion.Pdf.NET (latest version) | Syncfusion.Pdf.WinForms (latest version)* | +| **Additional** | .NET SDK installed from [.NET Downloads](https://dotnet.microsoft.com/en-us/download) | Visual Studio includes .NET Framework runtime | +| **License** | Syncfusion license key (required for production use) | Syncfusion license key (required for production use) | + +*Note: Syncfusion.Pdf.WinForms for .NET Framework console applications contains platform-independent PDF library assemblies (not Windows Forms-specific) and is suitable for console applications. + +## Getting Started Video + To quickly get started with the .NET PDF library, watch this video: {% youtube "https://youtu.be/PvUdu1hpRLQ?si=xFFjpsJZv3s8AonV" %} -## Steps to Create a PDF Document in a .NET (Core) Console App +--- + +## Steps to Create a PDF File in .NET 5.0 or Later + +Select your preferred development environment: + +### Visual Studio 2022, Visual Studio Code, or JetBrains Rider {% tabcontents %} {% tabcontent Visual Studio %} @@ -29,79 +49,127 @@ To quickly get started with the .NET PDF library, watch this video: {% endtabcontent %} {% endtabcontents %} -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Console/.NET/Create_PDF). +**License Registration:** Starting with v16.2.0.x, register your Syncfusion license key in `Program.cs` before creating PDF objects. Refer to the [Syncfusion licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for detailed instructions. + +A complete working sample can be downloaded from the [GitHub repository](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Console/.NET/Create_PDF). -By executing the program, you will get the PDF document as follows. +**Output:** Upon successful execution, you will get the PDF document as follows: ![Console output PDF document](GettingStarted_images/pdf-generation-output.png) -## Steps to Create a PDF Document in a .NET Framework Console App +--- -The following steps illustrates creating a simple Hello world PDF document in console application using .NET Framework. +## Steps to Create a PDF File in .NET Framework 4.5 or Later -**Prerequisites**: +The following steps illustrate creating a simple "Hello World" PDF document in a console application using .NET Framework. -* Install .NET SDK: Ensure that you have the .NET SDK installed on your system. You can download it from the [.NET Downloads page](https://dotnet.microsoft.com/en-us/download). -* Install Visual Studio: Download and install Visual Studio Code from the [official website](https://code.visualstudio.com/download). +**Step 1:** Create a new C# Console Application (.NET Framework) project. -Step 1: Create a new C# Console Application (.NET Framework) project. ![Console Application creation](Console_images/console-app-sample-creation.png) -Step 2: Name the project. +**Step 2:** Name the project. + ![Name the application](Console_images/Name_project_Framework.png) -Step 3: Install the [Syncfusion.Pdf.WinForms](https://www.nuget.org/packages/Syncfusion.Pdf.WinForms/) NuGet package as reference to your .NET Standard applications from [NuGet.org](https://www.nuget.org). +**Step 3:** Install the [Syncfusion.Pdf.WinForms](https://www.nuget.org/packages/Syncfusion.Pdf.WinForms/) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org). + ![NET Framework NuGet package](Console_images/Nuget_package_Framework.png) -N> The [Syncfusion.Pdf.WinForms](https://www.nuget.org/packages/Syncfusion.Pdf.WinForms/) NuGet package is a dependent package for Syncfusion® Windows Forms GUI controls, so named with suffix "WinForms". It has platform-independent .NET Framework (4.0, 4.5, 4.5.1, 4.6) assemblies of the PDF library and doesn't contain any Windows Forms-related references or code. Hence, we recommend this package for the .NET Framework Console application. +> **Note:** The Syncfusion.Pdf.WinForms NuGet package contains platform-independent .NET Framework assemblies of the PDF library. Despite its name, it does not contain any Windows Forms-specific references and is appropriate for console applications. -Step 4: Include the following namespaces in the *Program.cs*. +**Step 4:** Register your Syncfusion license key in the *Program.cs* file. Starting with v16.2.0.x, license registration is required. Refer to the [Syncfusion licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for instructions. + +**Step 5:** Include the following namespaces in *Program.cs*: {% tabs %} {% highlight c# tabtitle="C#" %} -using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf; +using Syncfusion.Pdf.Graphics; +using System; using System.Drawing; {% endhighlight %} {% endtabs %} -Step 5: Include the following code sample in *Program.cs* to create a PDF file. +**Step 6:** Add the following code to *Program.cs* to create a PDF file with error handling: {% tabs %} {% highlight c# tabtitle="C#" %} -//Create a new PDF document. -using (PdfDocument document = new PdfDocument()) +try +{ + // Create a new PDF document + using (PdfDocument document = new PdfDocument()) + { + // Add a page to the document + PdfPage page = document.Pages.Add(); + + // Create PDF graphics for the page + PdfGraphics graphics = page.Graphics; + + // Set the standard font + PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); + + // Draw text on the page + graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); + + // Save the document to the current directory + string outputPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Output.pdf"); + document.Save(outputPath); + + Console.WriteLine($"PDF created successfully at: {outputPath}"); + } +} +catch (Exception ex) { - //Add a page to the document. - PdfPage page = document.Pages.Add(); - //Create PDF graphics for a page. - PdfGraphics graphics = page.Graphics; - //Set the standard font. - PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); - //Draw the text. - graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); - //Save the document. - document.Save("Output.pdf"); + Console.WriteLine($"Error creating PDF: {ex.Message}"); } {% endhighlight %} {% endtabs %} -Step 6: Build the project. +**Step 7:** Build the project by clicking Build > Build Solution or pressing Ctrl + Shift + B. -Click on Build > Build Solution or press Ctrl + Shift + B to build the project. +**Step 8:** Run the project by clicking the Start button (green arrow) or pressing F5. -Step 7: Run the project. +Upon successful execution, the console will display the path where the PDF has been created. The output PDF file (`Output.pdf`) will be saved in the project's bin directory. -Click the Start button (green arrow) or press F5 to run the app. +A complete working sample can be downloaded from the [GitHub repository](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Console/.NET%20Framework/Create%20PDF). -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Console/.NET%20Framework/Create%20PDF). +**Output:** The executed program generates a PDF document with the text "Hello World!!!" formatted with Helvetica font: -By executing the program, you will get the PDF document as follows. ![Console output PDF document](GettingStarted_images/pdf-generation-output.png) -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. - -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +## Troubleshooting + +| Issue | Solution | +| --- | --- | +| "Could not load file or assembly 'Syncfusion.Pdf'" | Ensure the Syncfusion NuGet package is installed correctly: `dotnet add package Syncfusion.Pdf.NET` (.NET Core) or `Install-Package Syncfusion.Pdf.WinForms` (.NET Framework) | +| "License key is missing" or "License key expired" | Register your Syncfusion license key in Program.cs before creating PDF objects (Step 4 for .NET Framework, similar for .NET Core) | +| "Output.pdf not created in expected location" | The file is saved in the current working directory (bin folder when run from IDE, project directory when run from terminal) | +| "System.IO.FileNotFoundException" | Verify that the directory has write permissions and sufficient disk space is available | +| "The type 'PdfDocument' is not defined" | Ensure all required using statements are included (Syncfusion.Pdf, Syncfusion.Pdf.Graphics) | +| Application runs but PDF is empty or incomplete | Check that graphics.DrawString() is called before document.Save() and no exceptions occur | +| "Cannot find the .NET SDK" (.NET Core) | Install .NET SDK from [.NET Downloads](https://dotnet.microsoft.com/en-us/download) and verify PATH environment variable | +| File locked or cannot be overwritten | Close any open instances of Output.pdf before running the program again, or use a unique filename | +| Different output between .NET Core and Framework | Both versions should produce identical PDFs; check Syncfusion package versions match | +| NuGet package restore fails | Clear NuGet cache: `nuget locals all -clear` or use `dotnet nuget locals all --clear` | + +## Next Steps + +Explore advanced features and capabilities with the Syncfusion .NET PDF library: + +- [Merge PDF Documents](./merge-pdf-documents.md) - Combine multiple PDF files into one +- [Split PDF Documents](./split-pdf-documents.md) - Extract or divide PDF pages +- [Add Watermarks](./add-watermark.md) - Apply text and image watermarks to PDFs +- [Work with Forms](./fill-form-fields.md) - Create and fill interactive PDF forms +- [Add Images to PDF](./Working-with-Images.md) - Insert and manipulate images in PDFs +- [Add Digital Signatures](./digital-signatures.md) - Sign PDFs digitally +- [Secure Documents](./encrypt-pdf.md) - Encrypt and password-protect PDFs +- [Working with Tables and Grids](./Working-with-Tables.md) - Create formatted data tables +- [ASP.NET Core Web Application](./Create-PDF-file-in-ASP-NET-Core.md) - Generate PDFs in web applications +- [Other Platforms](../../getting-started.md) - PDF generation guides for other platforms (Docker, Linux, macOS, Cloud services) + +For additional examples and comprehensive API documentation, visit the [Syncfusion .NET PDF documentation](https://help.syncfusion.com/document-processing/pdf/overview). + +You can also explore our [interactive PDF demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) and the [Syncfusion PDF library features](https://www.syncfusion.com/document-sdk/net-pdf-library). \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-GCP.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-GCP.md index 61c1c7b619..6bc5976439 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-GCP.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-GCP.md @@ -6,27 +6,415 @@ control: PDF documentation: UG keywords: gcp os save pdf, gcp os load pdf, c# save pdf, c# load pdf --- -# Create a PDF document in Google Cloud Platform (GCP) +# Create a PDF File in Google Cloud Platform (GCP) -The [.NET Core PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, edit, and convert PDF documents programmatically without the dependency of Adobe Acrobat. Create a PDF document in Google Cloud Platform (GCP) using this library within a few lines of code. +The [.NET Core PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create, read, edit, and convert PDF documents programmatically in Google Cloud Platform without the dependency of Adobe Acrobat. This guide demonstrates how to generate and process PDF files in GCP using App Engine, a managed platform-as-a-service for deploying ASP.NET Core applications. -N> If this is your first time working with the Google Cloud Platform (GCP), please refer to the dedicated GCP resources. This section explains how to open and save a PDF document in C# using the .NET Core PDF library in GCP. +> **Note**: If this is your first time with Google Cloud Platform, review the [official GCP documentation](https://cloud.google.com/docs). This guide assumes familiarity with creating GCP projects and deploying .NET applications. For serverless PDF generation, see [Cloud Functions alternative](#alternative-gcp-services). -## Prerequisites +## Prerequisites -* A Google Cloud Platform (GCP) account with access to the App Engine service. +| Requirement | Details | +|-------------|---------| +| **IDE** | Visual Studio 2022 or Visual Studio Code | +| **.NET Version** | .NET 6.0+, .NET 7.0, or .NET 8.0 LTS | +| **GCP Service** | App Engine with .NET runtime support | +| **NuGet Package** | Syncfusion.Pdf.NET v16.2.0.x or later | +| **GCP Account** | Active Google Cloud account with billing enabled | +| **GCP Tools** | Google Cloud SDK with `gcloud` CLI tool installed and configured | +| **Licensing** | Syncfusion license key (required v16.2.0.x+) | +| **IAM Permissions** | App Engine Creator, Service Account User roles for deployment | -## Google Cloud Platform (GCP) +> **Tip**: GCP offers a [free tier](https://cloud.google.com/free) with 28 days of $300 credit and always-free App Engine quota (28 instance hours per day). - - - - - - -
-Google Cloud Platform
-NuGet package name
-App Engine
-{{'[Syncfusion.PDF.Net.Core](https://www.nuget.org/packages/Syncfusion.PDF.Net.Core)' | markdownify}}
-
\ No newline at end of file +## License Registration + +Starting with Syncfusion v16.2.0.x, a license key is required for PDF operations. Register your license in the `Program.cs` file before building services: + +```csharp +// In Program.cs - add this before var app = builder.Build(); +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); +``` + +> **Important**: Obtain a free community license from [Syncfusion Community License](https://help.syncfusion.com/common/essential-studio/licensing/community-license). For production GCP deployments, store the license key in [Secret Manager](https://cloud.google.com/secret-manager), never hardcode in source. Refer to [licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for details. + +## GCP Service Options + +This guide uses **Google Cloud App Engine** as the primary platform. Choose based on your requirements: + +| Service | Use Case | Scaling | Cost | +|---------|----------|---------|------| +| **App Engine (Recommended)** | ASP.NET Core web applications with PDF generation | Automatic | Pay-per-instance | +| **Cloud Functions** | Event-driven PDF generation (upload triggers) | Per-request | Pay-per-invocation | +| **Cloud Run** | Containerized PDF services with custom scaling | Per-request | Pay-per-request | +| **Compute Engine** | Full control, self-managed infrastructure | Manual | Pay-per-hour | + +This guide focuses on **App Engine** for its managed experience and native .NET support. For serverless alternatives, see [Cloud Functions](#cloud-functions-alternative). + +## Setting Up Your GCP Project + +**Step 1**: Create a new GCP project: +- Navigate to [Google Cloud Console](https://console.cloud.google.com/) +- Click **Select a Project** → **NEW PROJECT** +- Enter project name (e.g., `pdf-generation-service`) and click **CREATE** +- Wait for the project to be created, then select it + +**Step 2**: Enable required APIs: +- In the Cloud Console, navigate to **APIs & Services** → **Library** +- Search for and enable these APIs: + - **Google App Engine Admin API** + - **Cloud Build API** + - **App Engine flexible environment API** +- Each API takes 1-2 minutes to enable + +**Step 3**: Create a service account for deployment: +- Navigate to **APIs & Services** → **Credentials** +- Click **Create Credentials** → **Service Account** +- Enter service account name (e.g., `app-engine-deployer`) and click **CREATE AND CONTINUE** +- Grant roles: Select **App Engine Admin** and **Service Account User**, then click **CONTINUE** +- Click **DONE** to complete service account creation +- Download the JSON key file by clicking the service account name → **Keys** tab → **Add Key** → **Create new key** → **JSON** → **CREATE** + +**Step 4**: Configure GCP CLI credentials: +- Install [Google Cloud SDK](https://cloud.google.com/sdk/docs/install) if not already installed +- Run `gcloud init` and follow the prompts to authenticate +- Set your project: `gcloud config set project PROJECT_ID` (replace PROJECT_ID with your actual project ID) +- Set the path to your service account key: `gcloud auth activate-service-account --key-file=path/to/key.json` + +## Creating an ASP.NET Core Project for GCP App Engine + +**Step 5**: Create a new ASP.NET Core project: +```bash +dotnet new webapp -n PDFGenerationService +cd PDFGenerationService +``` + +**Step 6**: Install the Syncfusion.Pdf.NET NuGet package: +```bash +dotnet add package Syncfusion.Pdf.NET +``` + +**Step 7**: Create `app.yaml` configuration file in the project root to specify App Engine deployment settings: + +{% tabs %} + +{% highlight yaml tabtitle="app.yaml" %} + +runtime: dotnet +env: flex + +env_variables: + ASPNETCORE_ENVIRONMENT: "Production" + +# Specify scaling settings +automatic_scaling: + min_instances: 1 + max_instances: 5 + cpu_utilization: + target_utilization: 0.75 + +# Adjust resources for PDF processing (memory-intensive) +resources: + memory_gb: 2 + cpu: 1 + +{% endhighlight %} + +{% endtabs %} + +> **Note**: The `app.yaml` file tells GCP how to deploy your application. Adjust `memory_gb` (default 0.5, increased to 2 for PDF operations) and `max_instances` based on expected load. + +## Implementing PDF Generation + +**Step 8**: Update `Program.cs` to register the Syncfusion license and configure services: + +{% tabs %} + +{% highlight c# tabtitle="C#" %} + +var builder = WebApplication.CreateBuilder(args); + +// Register Syncfusion license (required for v16.2.0.x+) +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + +// Add services to the container +builder.Services.AddControllersWithViews(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline +if (!app.Environment.IsDevelopment()) +{ + app.UseExceptionHandler("/Home/Error"); + app.UseHsts(); +} + +app.UseHttpsRedirection(); +app.UseStaticFiles(); +app.UseRouting(); +app.UseAuthorization(); + +app.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); + +app.Run(); + +{% endhighlight %} + +{% endtabs %} + +**Step 9**: Add the required namespaces and create a `PdfController.cs` file: + +{% tabs %} + +{% highlight c# tabtitle="C#" %} + +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.AspNetCore.Mvc; +using Syncfusion.Pdf; +using Syncfusion.Pdf.Graphics; +using Syncfusion.Pdf.Grid; +using Syncfusion.Drawing; + +{% endhighlight %} + +{% endtabs %} + +**Step 10**: Implement the PDF generation method in `PdfController.cs`: + +{% tabs %} + +{% highlight c# tabtitle="C#" %} + +[ApiController] +[Route("api/[controller]")] +public class PdfController : ControllerBase +{ + private readonly IWebHostEnvironment _hostEnvironment; + private readonly ILogger _logger; + + public PdfController(IWebHostEnvironment hostEnvironment, ILogger logger) + { + _hostEnvironment = hostEnvironment; + _logger = logger; + } + + [HttpPost("generate")] + public IActionResult GeneratePDF() + { + try + { + _logger.LogInformation("Starting PDF generation"); + + // Create a new PDF document + using (PdfDocument document = new PdfDocument()) + { + // Add a new page + PdfPage page = document.Pages.Add(); + PdfGraphics graphics = page.Graphics; + PdfFont titleFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20, PdfFontStyle.Bold); + PdfFont bodyFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); + + // Add title + graphics.DrawString("Product Inventory Report", titleFont, PdfBrushes.Black, new PointF(50, 50)); + + // Create product data table + List productData = new List + { + new { Product_ID = "1001", Product_Name = "Bicycle", Price = "$10,000", Stock = "15" }, + new { Product_ID = "1002", Product_Name = "Head Light", Price = "$3,000", Stock = "25" }, + new { Product_ID = "1003", Product_Name = "Brake Wire", Price = "$1,500", Stock = "50" }, + new { Product_ID = "1004", Product_Name = "Pedal Set", Price = "$2,000", Stock = "30" }, + new { Product_ID = "1005", Product_Name = "Chain", Price = "$500", Stock = "100" } + }; + + // Create and format PDF grid (table) + PdfGrid pdfGrid = new PdfGrid(); + pdfGrid.DataSource = productData; + pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); + + // Draw table on the page + PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat(); + layoutFormat.Layout = PdfLayoutType.Paginate; + pdfGrid.Draw(page, new RectangleF(50, 100, page.ClientSize.Width - 100, 0), layoutFormat); + + // Add footer with timestamp + graphics.DrawString($"Generated on: {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC", bodyFont, PdfBrushes.Gray, + new PointF(50, page.ClientSize.Height - 50)); + + // Save to memory stream + using (MemoryStream memoryStream = new MemoryStream()) + { + document.Save(memoryStream); + memoryStream.Position = 0; + _logger.LogInformation($"PDF generated successfully. Size: {memoryStream.Length} bytes"); + return File(memoryStream.ToArray(), "application/pdf", "ProductReport.pdf"); + } + } + } + catch (Exception ex) + { + _logger.LogError($"Error generating PDF: {ex.Message}"); + return StatusCode(500, new { error = $"PDF generation failed: {ex.Message}" }); + } + } +} + +{% endhighlight %} + +{% endtabs %} + +> **Important Notes**: +> - Register the Syncfusion license in `Program.cs` BEFORE creating any PDF objects +> - Use dependency injection for `IWebHostEnvironment` and `ILogger` for logging +> - All streams are wrapped in `using` statements for proper resource disposal in GCP environment +> - Error responses include detailed logging for GCP Cloud Logging integration +> - The `[HttpPost("generate")]` endpoint accepts POST requests to generate PDFs + +## Deploying to Google Cloud App Engine + +**Step 11**: Test your application locally before deployment: +```bash +dotnet run +``` +The application will run at `http://localhost:5000`. Navigate to `http://localhost:5000/api/pdf/generate` to test PDF generation. + +**Step 12**: Deploy to Google Cloud App Engine using the gcloud CLI: +```bash +gcloud app deploy +``` + +The deployment process will: +- Build your application +- Upload to Google Cloud Storage +- Deploy to App Engine +- Show your application URL (e.g., `https://PROJECT_ID.appspot.com`) + +**Step 13**: Verify deployment status: +```bash +gcloud app browse +``` +This opens your deployed application in the default browser. + +**Step 14**: Monitor deployment logs: +```bash +gcloud app logs read -n 50 +``` +View application logs in [Cloud Console](https://console.cloud.google.com/appengine/services) or use [Cloud Logging](https://console.cloud.google.com/logs): +- Navigate to **Cloud Logging** → **Logs Explorer** +- Filter by resource type: **App Engine** +- Search for errors or performance issues + +## Testing the Deployed Application + +**Step 15**: Test the deployed PDF generation endpoint. Use curl: +```bash +curl -X POST https://PROJECT_ID.appspot.com/api/pdf/generate -o output.pdf +``` + +Or use a tool like [Postman](https://www.postman.com/): +1. Create a new POST request to `https://PROJECT_ID.appspot.com/api/pdf/generate` +2. Send the request +3. Download the returned PDF file + +**Step 16**: Verify the generated PDF: +- The downloaded file should be named `ProductReport.pdf` +- Should contain the product table with 5 sample items +- Should include a timestamp footer with generation date/time UTC +- File size should be 5-10 KB depending on content + +## Expected Output + +When you execute the PDF generation endpoint, you will receive: +- A downloadable PDF file named `ProductReport.pdf` +- Contains a formatted product inventory table with columns: Product_ID, Product_Name, Price, Stock +- Title: "Product Inventory Report" +- Professional table styling (GridTable4Accent3) +- Footer with generation timestamp in UTC +- Response status: 200 OK with binary PDF data +- Error responses include JSON error message and status 500 + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| **License Key Not Registered** | Verify `SyncfusionLicenseProvider.RegisterLicense()` is called in `Program.cs` BEFORE service building. Check that your license key is valid and matches your .NET version. | +| **"APIs not enabled" error during deployment** | In Google Cloud Console, navigate to **APIs & Services** → **Library**. Search for and enable: Google App Engine Admin API, Cloud Build API, App Engine flexible environment API. Wait 1-2 minutes for activation. | +| **Syncfusion.Pdf.NET Package Not Found** | Run `dotnet add package Syncfusion.Pdf.NET` in your project directory. Verify v16.2.0.x or later is installed: `dotnet list package`. | +| **"Permission denied" when deploying** | Verify your GCP service account has **App Engine Admin** and **Service Account User** roles. Check: `gcloud projects get-iam-policy PROJECT_ID`. | +| **App Engine deployment timeout** | Increase timeout: Run `gcloud config set app/cloud_build_timeout 1800` to extend to 30 minutes. Check Cloud Build logs in **Cloud Console** → **Cloud Build** for build errors. | +| **Memory limit exceeded (OutOfMemoryException)** | Increase memory in `app.yaml`: Change `memory_gb` from 2 to 4 (or higher). Monitor: **Cloud Console** → **App Engine** → **Instances** tab for memory usage. Large PDFs need more memory. | +| **HTTP 500 error after deployment** | Check logs: `gcloud app logs read -n 100` or use **Cloud Logging** console. Verify Syncfusion license key is correct for production environment. Check for missing or incorrect appsettings in `Program.cs`. | +| **"Could not resolve NuGet package" during build** | Ensure `dotnet restore` completes locally before deploying. Check that nuget.org is accessible. Clear NuGet cache: `dotnet nuget locals all --clear` and retry. | +| **Licensing error after 30 days** | Development license keys expire. For production, use a production license key from Syncfusion. Refer to [licensing overview](https://help.syncfusion.com/common/essential-studio/licensing/overview). | +| **Slow PDF generation on first request** | App Engine "cold starts" (~5-10s) are normal. Subsequent requests are faster (~100ms). Increase `min_instances` in `app.yaml` to keep instances warm, but this increases costs. | + +## Next Steps + +Explore advanced PDF capabilities and GCP integration patterns: + +### Advanced PDF Features +- **[Merge Multiple PDFs](https://help.syncfusion.com/file-formats/pdf/working-with-documents/merge-documents)** — Combine multiple PDF documents into a single file +- **[Split PDF Documents](https://help.syncfusion.com/file-formats/pdf/split-document)** — Extract specific pages from PDF files +- **[Add Watermarks](https://help.syncfusion.com/file-formats/pdf/working-with-pages/add-watermark)** — Add company logos or confidentiality markers +- **[Create Interactive Forms](https://help.syncfusion.com/file-formats/pdf/working-with-forms/overview)** — Build fillable PDF forms for data collection +- **[Digital Signatures](https://help.syncfusion.com/file-formats/pdf/working-with-forms/create-digital-signatures)** — Sign PDFs programmatically for compliance +- **[PDF Encryption](https://help.syncfusion.com/file-formats/pdf/working-with-security/encrypt-pdf)** — Protect PDFs with passwords and permissions + +### GCP Integration Patterns +- **[Cloud Storage Integration](https://cloud.google.com/storage/docs)** — Store generated PDFs in GCS buckets; reference in downloads +- **[Cloud Pub/Sub Event Processing](https://cloud.google.com/pubsub)** — Process PDF generation requests from message queues +- **[Cloud Tasks Scheduling](https://cloud.google.com/tasks)** — Schedule batch PDF generation jobs +- **[Firestore Database](https://cloud.google.com/firestore)** — Store PDF metadata and generation history +- **[Cloud CDN](https://cloud.google.com/cdn)** — Cache and deliver generated PDFs globally with low latency +- **[IAM Access Control](https://cloud.google.com/iam)** — Restrict PDF generation endpoints to authenticated users + +### Cloud Functions Alternative + +For **serverless, event-driven PDF generation** (pay-per-invocation, no cold start), use [Google Cloud Functions](https://cloud.google.com/functions) instead: + +```bash +# Deploy a Cloud Function for PDF generation +gcloud functions deploy GeneratePDF \ + --runtime dotnet8 \ + --trigger-http \ + --allow-unauthenticated +``` + +Use Cloud Functions for: +- S3-triggered PDF generation (when files are uploaded) +- Scheduled batch jobs (Pub/Sub scheduled messages) +- Microservice architecture (decomposed workloads) +- Cost optimization (pay only for invocations, no idle instance costs) + +### Deployment and Operations +- **[App Engine Scaling](https://cloud.google.com/appengine/docs/flexible/dotnet/configuring-your-app-with-app-yaml)** — Configure min/max instances and CPU utilization thresholds +- **[Cloud Monitoring](https://cloud.google.com/monitoring)** — Set up alerts for error rates, latency, memory usage +- **[Cloud Profiler](https://cloud.google.com/profiler)** — Identify performance bottlenecks in PDF generation +- **[Error Reporting](https://cloud.google.com/error-reporting)** — Automatically aggregate and alert on exceptions +- **[GCP Cost Management](https://cloud.google.com/cost-management)** — Monitor App Engine costs; use budget alerts +- **[CI/CD with Cloud Build](https://cloud.google.com/build)** — Automate testing and deployment on code commits + +## Resources + +**Sample Code:** +- [Complete GCP App Engine example](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/GCP/AppEngine) +- [GCP Cloud Functions example](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/GCP/CloudFunctions) + +**Documentation:** +- [Syncfusion .NET PDF Library Guide](https://help.syncfusion.com/file-formats/pdf/) +- [Google Cloud App Engine for .NET](https://cloud.google.com/appengine/docs/flexible/dotnet) +- [Deploying ASP.NET Core to App Engine](https://cloud.google.com/appengine/docs/flexible/dotnet/create-app) +- [Google Cloud SDK Documentation](https://cloud.google.com/sdk/docs) +- [Cloud Console](https://console.cloud.google.com/) — Manage GCP resources +- [Licensing Overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) + +**Try It Out:** +- [Syncfusion PDF Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) +- [Explore Syncfusion PDF Features](https://www.syncfusion.com/document-sdk/net-pdf-library) +- [GCP Free Tier](https://cloud.google.com/free) — $300 credit + always-free App Engine quota +- [Cloud Shell (Browser-based terminal)](https://cloud.google.com/shell) — No local gcloud CLI installation needed \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Google-App-Engine.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Google-App-Engine.md index b3e939102d..2370ccab6e 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Google-App-Engine.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Google-App-Engine.md @@ -1,75 +1,171 @@ --- -title: Create or Generate PDF document in Google App Engine| Syncfusion -description: Learn how to create or generate a PDF file in the Google App Engine using Syncfusion .NET Core PDF library without the dependency of Adobe Acrobat. +title: Create or Generate PDF file in Google App Engine | Syncfusion +description: Learn how to create or generate a PDF file in Google App Engine using Syncfusion .NET PDF library without the dependency of Adobe Acrobat. platform: document-processing control: PDF documentation: UG -keywords: google app engine save pdf, app engine load pdf, c# save pdf, c# load pdf +keywords: google app engine save pdf, app engine load pdf, c# save pdf, c# load pdf, app engine pdf generation, aspnet core pdf --- -# Create a PDF document in Google App Engine +# Create a PDF File in Google App Engine -The [.NET Core PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents programmatically without the dependency on Adobe Acrobat. Using this library, you can open and save PDF documents in Google App Engine. +The [.NET Core PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create, read, edit, and convert PDF documents programmatically in Google App Engine without the dependency of Adobe Acrobat. This guide demonstrates how to generate and process PDF files using ASP.NET Core applications deployed on Google App Engine's managed platform. -**Set up App Engine** +> **Note**: This guide uses Google Cloud Shell for deployment. If you are new to Google Cloud Platform, refer to the [GCP documentation](https://cloud.google.com/docs). This section assumes you have a GCP account and basic familiarity with cloud deployments. + +## Prerequisites + +| Requirement | Details | +|-------------|---------| +| **IDE** | Visual Studio 2022 or Visual Studio Code | +| **.NET Version** | .NET 6.0+, .NET 7.0, or .NET 8.0 LTS | +| **.NET SDK** | .NET 8.0 SDK or later (for local development) | +| **NuGet Package** | Syncfusion.Pdf.NET v16.2.0.x or later | +| **GCP Account** | Active Google Cloud account with billing enabled | +| **GCP Project** | Created GCP project with App Engine API enabled | +| **Docker** | Docker Desktop installed locally (optional; can use Cloud Shell editor) | +| **Licensing** | Syncfusion license key (required v16.2.0.x+) | + +> **Tip**: GCP offers a [free tier](https://cloud.google.com/free) with 28 days of $300 credit and always-free App Engine flexible environment quota. + +## License Registration + +Starting with Syncfusion v16.2.0.x, a license key is required for PDF operations. Register your license in the `Program.cs` file before building services: + +```csharp +// In Program.cs - add this before var app = builder.Build(); +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); +``` + +> **Important**: Obtain a free community license from [Syncfusion Community License](https://help.syncfusion.com/common/essential-studio/licensing/community-license). For production GCP deployments, store the license key in [Secret Manager](https://cloud.google.com/secret-manager), never hardcode in source. Refer to [licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for details. + +## Setting Up Google Cloud Platform (GCP) + +**Step 1**: Create a new GCP project (if not already created): +- Navigate to [Google Cloud Console](https://console.cloud.google.com/) +- Click **Select a Project** → **NEW PROJECT** +- Enter project name (e.g., `pdf-generation-app`) and click **CREATE** +- Select the project after creation + +**Step 2**: Enable required APIs: +- In the Cloud Console, navigate to **APIs & Services** → **Library** +- Search for and enable: **Google App Engine Admin API** and **Cloud Build API** +- Each API takes 1-2 minutes to enable + +**Step 3**: Open the **Google Cloud Console** and click the **Activate Cloud Shell** button. -Step 1: Open the **Google Cloud Console** and click the **Activate Cloud Shell** button. ![Activate Cloud Shell](GettingStarted_images/Google_Cloud_Console.png) -Step 2: Click the **Cloud Shell Editor** button to view the **Workspace**. +**Step 4**: Click the **Cloud Shell Editor** button to view the workspace. + ![Open Editor in Cloud Shell](GettingStarted_images/Cloud_Shell.png) -Step 3: Open **Cloud Shell Terminal**, and run the following **command** to confirm authentication. -{% tabs %} -{% highlight c# tabtitle="CLI" %} +**Step 5**: In the Cloud Shell Terminal, run the following command to confirm authentication: +```bash gcloud auth list - -{% endhighlight %} -{% endtabs %} +``` ![Authentication for App Engine](GettingStarted_images/Authorize_Command.png) -Step 4: Click the **Authorize** button. +**Step 6**: If prompted, click the **Authorize** button to grant permissions. + ![Click Authorize button](GettingStarted_images/Authorize_Button.png) -**Create an application for App Engine** +## Creating an ASP.NET Core Project for App Engine + +**Step 7**: Open Visual Studio 2022 and create a new ASP.NET Core Web App (Model-View-Controller) project: +- Click **Create a new project** → Search for "ASP.NET Core Web App (Model-View-Controller)" +- Select the template and click **Next** -Step 1: Open Visual Studio and select the ASP.NET Core Web app (Model-View-Controller) template. ![Create ASP.NET Core Web application in Visual Studio](GettingStarted_images/Create-Project.png) -Step 2: Configure your new project according to your requirements. -![Create ASP.NET Core Web application in Visual Studio](GettingStarted_images/Project-Name.png) +**Step 8**: Configure your project: +- Project name: `PDFGenerationApp` (or your preferred name) +- Location: Choose a local directory +- Click **Next** + +![Configure ASP.NET Core Web application](GettingStarted_images/Project-Name.png) -Step 3: Click the **Create** button. -![Create ASP.NET Core Web application in Visual Studio](GettingStarted_images/Additional-Information.png) +**Step 9**: Select the target framework (**.NET 8.0** recommended) and click **Create**. + +![Select framework for ASP.NET Core](GettingStarted_images/Additional-Information.png) + +**Step 10**: Install the Syncfusion.Pdf.NET NuGet package: +```bash +dotnet add package Syncfusion.Pdf.NET +``` + +Or use Package Manager UI: +- Tools → NuGet Package Manager → Package Manager Console +- Run: `Install-Package Syncfusion.Pdf.NET` -Step 4: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core/) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). ![Install Syncfusion.Pdf.Net.Core NuGet package](GettingStarted_images/Google-NuGet-Package.png) -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from the trial setup or from the NuGet feed, you also have to add the "Syncfusion.Licensing" assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to learn about registering the Syncfusion® license key in your application to use our components. +**Step 11**: Update `Program.cs` to register the Syncfusion license: + +{% tabs %} + +{% highlight c# tabtitle="Program.cs" %} -Step 5: Include the following namespaces in the **HomeController.cs** file. +var builder = WebApplication.CreateBuilder(args); + +// Register Syncfusion license (required for v16.2.0.x+) +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + +builder.Services.AddControllersWithViews(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +if (!app.Environment.IsDevelopment()) +{ + app.UseExceptionHandler("/Home/Error"); + app.UseHsts(); +} + +app.UseHttpsRedirection(); +app.UseStaticFiles(); +app.UseRouting(); +app.UseAuthorization(); + +app.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); + +app.Run(); + +{% endhighlight %} + +{% endtabs %} + +**Step 12**: Add required namespaces to `HomeController.cs`: {% tabs %} + {% highlight c# tabtitle="C#" %} +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.AspNetCore.Mvc; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; +using Syncfusion.Pdf.Grid; using Syncfusion.Drawing; -using System.IO; {% endhighlight %} -{% endtabs %} -Step 6: A default action method named Index will be present in HomeController.cs. Right click on Index method and select **Go To View** where you will be directed to its associated view page **Index.cshtml**. +{% endtabs %} -Step 7: Add a new button in the Index.cshtml as shown in the following. +**Step 13**: In `Index.cshtml`, add a button to trigger PDF generation: {% tabs %} -{% highlight CSHTML %} -@{Html.BeginForm("CreateDocument", "Home", FormMethod.Get); +{% highlight html tabtitle="CSHTML" %} + +@{ + Html.BeginForm("CreateDocument", "Home", FormMethod.Post); {
@@ -77,211 +173,335 @@ Step 7: Add a new button in the Index.cshtml as shown in the following. } Html.EndForm(); } + {% endhighlight %} + {% endtabs %} -Step 8: Add a new action method **CreateDocument** in HomeController.cs and include the following code sample to **create PDF document** and download it. +> **Note**: Use `FormMethod.Post` for operations that generate and download files, not GET. This is the correct HTTP method for file downloads. + +**Step 14**: Add the PDF generation controller method to `HomeController.cs`: {% tabs %} + {% highlight c# tabtitle="C#" %} -public ActionResult CreateDocument() +[HttpPost] +public IActionResult CreateDocument() { - //Load PDF document as stream. - using FileStream docStream = new FileStream(@"Data/Input.pdf", FileMode.Open, FileAccess.Read); - //Load an existing PDF document. - PdfLoadedDocument document = new PdfLoadedDocument(docStream); - - //Load the existing page. - PdfLoadedPage loadedPage = document.Pages[0] as PdfLoadedPage; - //Create PDF graphics for the page. - PdfGraphics graphics = loadedPage.Graphics; - - //Create a PdfGrid. - PdfGrid pdfGrid = new PdfGrid(); - //Add values to the list. - List data = new List(); - Object row1 = new { Product_ID = "1001", Product_Name = "Bicycle", Price = "10,000" }; - Object row2 = new { Product_ID = "1002", Product_Name = "Head Light", Price = "3,000" }; - Object row3 = new { Product_ID = "1003", Product_Name = "Break wire", Price = "1,500" }; - data.Add(row1); - data.Add(row2); - data.Add(row3); - //Add list to IEnumerable. - IEnumerable dataTable = data; - //Assign data source. - pdfGrid.DataSource = dataTable; - //Apply built-in table style. - pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); - //Draw the grid to the page of PDF document. - pdfGrid.Draw(graphics, new RectangleF(40, 400, loadedPage.Size.Width - 80, 0)); - - //Create memory stream. - MemoryStream stream = new MemoryStream(); - //Save the PDF document to stream. - document.Save(stream); - //If the position is not set to '0' then the PDF will be empty. - stream.Position = 0; - //Close the document. - document.Close(true); - //Download PDF document in the browser. - return File(stream, "application/pdf", "Sample.pdf"); + try + { + string inputPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Data", "Input.pdf"); + + // Verify input file exists + if (!System.IO.File.Exists(inputPath)) + { + ViewBag.Message = $"Error: Input PDF file not found at {inputPath}"; + return View("Index"); + } + + // Load input PDF with proper resource disposal + using (FileStream fileStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read)) + { + using (PdfLoadedDocument document = new PdfLoadedDocument(fileStream)) + { + // Load the first page and get graphics + PdfLoadedPage loadedPage = document.Pages[0] as PdfLoadedPage; + PdfGraphics graphics = loadedPage.Graphics; + + // Create product data + List productData = new List + { + new { Product_ID = "1001", Product_Name = "Bicycle", Price = "$10,000" }, + new { Product_ID = "1002", Product_Name = "Head Light", Price = "$3,000" }, + new { Product_ID = "1003", Product_Name = "Brake Wire", Price = "$1,500" }, + new { Product_ID = "1004", Product_Name = "Pedal Set", Price = "$2,000" }, + new { Product_ID = "1005", Product_Name = "Chain", Price = "$500" } + }; + + // Create and format PDF grid (table) + PdfGrid pdfGrid = new PdfGrid(); + pdfGrid.DataSource = productData; + pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); + + // Draw grid to the page + pdfGrid.Draw(graphics, new RectangleF(40, 400, loadedPage.Size.Width - 80, 0)); + + // Save to memory stream with proper disposal + using (MemoryStream stream = new MemoryStream()) + { + document.Save(stream); + stream.Position = 0; + return File(stream.ToArray(), "application/pdf", "ProductReport.pdf"); + } + } + } + } + catch (Exception ex) + { + ViewBag.Message = $"Error generating PDF: {ex.Message}"; + return View("Index"); + } } {% endhighlight %} + {% endtabs %} -**Move application to App Engine** +> **Important Notes**: +> - All streams and documents are wrapped in `using` statements for guaranteed resource disposal +> - The `[HttpPost]` attribute matches the form method from Step 13 +> - File existence validation prevents crashes if Input.pdf is missing +> - Error handling with ViewBag ensures graceful failure with user-friendly messages +> - Input PDF must be placed at `wwwroot/Data/Input.pdf` in your project -Step 1: Open the **Cloud Shell editor**. +**Step 15**: Create the `wwwroot/Data/` folder in your project: +- Right-click your project → Add → New Folder → Name it `wwwroot/Data` +- Add or create an `Input.pdf` file in this folder +- Right-click the PDF → Properties → Set **Copy to Output Directory** to "Copy if newer" -![Cloud Shell editor](GettingStarted_images/Cloud_Shell_Editor.png) +## Uploading Project to Google Cloud Shell -Step 2: Drag and drop the sample from your local machine to **Workspace**. +**Step 16**: Open the **Cloud Shell Editor**: +- In Google Cloud Console, click **Activate Cloud Shell** +- Click the **Editor** button to open Cloud Shell Editor -![Add Project](GettingStarted_images/Add_Project.png) +![Cloud Shell editor](GettingStarted_images/Cloud_Shell_Editor.png) -N> If you have your sample application in your local machine, drag and drop it into the Workspace. If you created the sample using the Cloud Shell terminal command, it will be available in the Workspace. +**Step 17**: Upload your local project to Cloud Shell: +- Drag and drop your `PDFGenerationApp` folder into the Cloud Shell workspace +- Alternatively, use Git: `git clone ` -Step 3: Open the Cloud Shell Terminal and run the following **command** to view the files and directories within your **current Workspace**. +> **Note**: If you developed locally, upload the entire project directory. The `bin` and `obj` folders will be regenerated during build. -{% tabs %} -{% highlight bash %} +![Add Project](GettingStarted_images/Add_Project.png) +**Step 18**: In the Cloud Shell Terminal, verify the project structure: +```bash ls - -{% endhighlight %} -{% endtabs %} +``` ![ls command](GettingStarted_images/ls_Command.png) -Step 4: Run the following **command** to navigate which sample you want to run. - -{% tabs %} -{% highlight bash %} - -cd Web_Application - -{% endhighlight %} -{% endtabs %} +**Step 19**: Navigate to your project directory: +```bash +cd PDFGenerationApp +``` ![Project Folder](GettingStarted_images/Project_Folder.png) -Step 5: To ensure that the sample is working correctly, please run the application using the following command. - -{% tabs %} -{% highlight bash %} +## Testing Locally in Cloud Shell +**Step 20**: Run the application locally in Cloud Shell to verify it works: +```bash dotnet run --urls=http://localhost:8080 - -{% endhighlight %} -{% endtabs %} +``` ![Run Application](GettingStarted_images/Run_Application.png) -Step 6: Verify that the application is running properly by accessing the **Web View -> Preview on port 8080**. +**Step 21**: Verify the application is running by clicking **Web Preview** → **Preview on port 8080**: ![Preview on Port](GettingStarted_images/Preview.png) -Step 7: Now you can see the sample output on the preview page. +**Step 22**: You should see the ASP.NET Core application homepage with the "Create PDF Document" button. Click the button to test PDF generation. ![Output Button](GettingStarted_images/Console_Page.png) -Step 8: Close the preview page and return to the terminal then press **Ctrl+C** for which will typically stop the process. - -![Work space](GettingStarted_images/Run_View.png) - -**Publish the application** +**Step 23**: Stop the local test server by pressing **Ctrl+C** in the Cloud Shell Terminal: -Step 1: Run the following command in the **Cloud Shell Terminal** to publish the application. +![Stop Application](GettingStarted_images/Run_View.png) -{% tabs %} -{% highlight bash %} +## Publishing and Configuring for Deployment +**Step 24**: Publish the application in Release configuration: +```bash dotnet publish -c Release - -{% endhighlight %} -{% endtabs %} +``` ![Release](GettingStarted_images/Publish_GCP.png) -Step 2: Run the following command in the **Cloud Shell Terminal** to navigate to the publish folder. - -{% tabs %} -{% highlight bash %} - +**Step 25**: Navigate to the publish output directory: +```bash cd bin/Release/net8.0/publish/ - -{% endhighlight %} -{% endtabs %} +``` ![Publish Folder](GettingStarted_images/Publish_Folder.png) -**Configure app.yaml and docker file** +**Step 26**: Create `app.yaml` configuration file for App Engine deployment in the publish folder: -Step 1: Add the app.yaml file to the publish folder with the following contents. +Create a file named `app.yaml` with the following contents: {% tabs %} -{% highlight bash %} -cat <> app.yaml +{% highlight yaml tabtitle="app.yaml" %} + env: flex -runtime: custom -EOT +runtime: custom + +# Scaling configuration for App Engine flexible environment +automatic_scaling: + min_instances: 1 + max_instances: 5 + cpu_utilization: + target_utilization: 0.75 + +# Memory and CPU resources for PDF processing +resources: + memory_gb: 2 + cpu: 1 {% endhighlight %} + {% endtabs %} -![yaml file to publish](GettingStarted_images/App_yaml.png) +> **Note**: The `app.yaml` file configures App Engine deployment. Set `memory_gb: 2` for PDF operations (default 0.5 is too low). +![app.yaml file](GettingStarted_images/App_yaml.png) -Step 2: Add the Docker file to the publish folder with the following contents. +**Step 27**: Create `Dockerfile` in the publish folder with the following contents: {% tabs %} -{% highlight bash %} -cat <> Dockerfile +{% highlight dockerfile tabtitle="Dockerfile" %} + FROM mcr.microsoft.com/dotnet/aspnet:8.0 -RUN apt-get update -y && apt-get install libfontconfig -y +RUN apt-get update -y && apt-get install -y libfontconfig ADD / /app EXPOSE 8080 ENV ASPNETCORE_URLS=http://*:8080 WORKDIR /app -ENTRYPOINT [ "dotnet", "Web_Application.dll"] -EOT +ENTRYPOINT ["dotnet", "PDFGenerationApp.dll"] {% endhighlight %} -{% endtabs %} -![Docker file to publish](GettingStarted_images/Docker_File.png) +{% endtabs %} -Step 3: You can ensure **Docker** and **app.yaml** files are added in **Workspace**. +> **Important Notes**: +> - `libfontconfig` is required for PDF font rendering in Linux containers +> - Replace `PDFGenerationApp.dll` with your actual project DLL name +> - The Docker image is based on .NET 8.0 ASP.NET Core runtime +> - Port 8080 must match the port in `app.yaml` -![Docker file](GettingStarted_images/Docker.png) +![Dockerfile](GettingStarted_images/Docker_File.png) -**Deploy to App Engine** +**Step 28**: Verify both files are created in the publish folder: +```bash +ls -la *.yaml *.dockerfile +``` -Step 1: To deploy the application to the App Engine, run the following command in Cloud Shell Terminal. Afterwards, retrieve the **URL** from the Cloud Shell Terminal. +![Docker and app.yaml files](GettingStarted_images/Docker.png) -{% tabs %} -{% highlight bash %} +## Deploying to Google App Engine +**Step 29**: Deploy your application to Google App Engine. In the publish folder, run: +```bash gcloud app deploy --version v0 +``` -{% endhighlight %} -{% endtabs %} +This command will: +1. Build a Docker image from the Dockerfile +2. Push it to Google Container Registry +3. Deploy to App Engine flexible environment +4. Provide your application URL (e.g., `https://PROJECT_ID.appspot.com`) -![Deploy](GettingStarted_images/Deploy.png) -![Get URL](GettingStarted_images/Get_deploy_url.png) +![Deploy command](GettingStarted_images/Deploy.png) -Step 2: Open the **URL** to access the application, which has been successfully deployed. +**Step 30**: After deployment completes, retrieve your application URL from the terminal output. Open it in a browser: -![Output Console](GettingStarted_images/Console_Page.png) +``` +https://PROJECT_ID.appspot.com +``` -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/GCP/Google_App_Engine). +![Get URL](GettingStarted_images/Get_deploy_url.png) + +**Step 31**: Open the deployed application URL to verify it's running. You should see the homepage with the "Create PDF Document" button. -By executing the program, you will get the **PDF document** as follows. The output will be saved in the **bin folder**. +![Output Console](GettingStarted_images/Console_Page.png) -![Output PDF Document](GettingStarted_images/Open_and_save_output.png) +## Testing the Deployed Application + +**Step 32**: Click the **Create PDF Document** button on your deployed application to generate a PDF. + +**Step 33**: The application will: +1. Load the input PDF from `wwwroot/Data/Input.pdf` +2. Add a product table to the first page +3. Generate the final PDF +4. Download it as `ProductReport.pdf` + +**Step 34**: Verify the downloaded PDF contains: +- A product inventory table with 5 sample items +- Professional table styling +- All original content from the input PDF + +## Expected Output + +When you click "Create PDF Document" on the deployed application, the browser will: +- Display download prompt or auto-download `ProductReport.pdf` +- File should be 5-15 KB depending on input PDF size +- Contains product table with columns: Product_ID, Product_Name, Price +- Response status: 200 OK (successful download) +- Error responses show error message on the application page + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| **License Key Not Registered** | Verify `SyncfusionLicenseProvider.RegisterLicense()` is called in `Program.cs` BEFORE service building. License registration is required for v16.2.0.x+. | +| **"Input PDF file not found" error** | Ensure `wwwroot/Data/Input.pdf` exists in the project. Set file's **Copy to Output Directory** to "Copy if newer". Upload this folder to Cloud Shell. | +| **Syncfusion.Pdf.NET Package Not Found** | Run `dotnet add package Syncfusion.Pdf.NET` locally before uploading. Verify v16.2.0.x or later: `dotnet list package`. | +| **Docker build fails with "libfontconfig not found"** | The `Dockerfile` includes `apt-get install libfontconfig` to provide font support for PDF rendering in Linux containers. Ensure this line is not commented. | +| **App Engine deployment timeout** | Deployment can take 10-15 minutes. Check Cloud Build logs: **Cloud Console** → **Cloud Build** → View build status. Increase timeout: `gcloud config set app/cloud_build_timeout 1800`. | +| **HTTP 500 error after deployment** | Check logs: `gcloud app logs read -n 100`. Verify license key is correct in `Program.cs`. Check that all required namespaces are imported. | +| **"Permission denied" during deployment** | Ensure your GCP project ID is set: `gcloud config set project PROJECT_ID`. Verify your account has App Engine Admin role in IAM. | +| **OutOfMemoryException (PDF generation fails)** | Increase memory in `app.yaml`: Change `memory_gb` from 2 to 4. Large PDFs need more memory. Monitor in **Cloud Console** → **App Engine** → **Instances**. | +| **DLL name mismatch in Docker** | Error: "Could not load file or assembly 'Web_Application.dll'". Verify ENTRYPOINT in Dockerfile matches your actual DLL: `dotnet PDFGenerationApp.dll`. | +| **Licensing error in production** | Development license keys expire after 30 days. For production, use a production license from Syncfusion or request deployment support. See [licensing overview](https://help.syncfusion.com/common/essential-studio/licensing/overview). | + +## Next Steps + +Explore advanced PDF capabilities and GCP App Engine integration patterns: + +### Advanced PDF Features +- **[Merge Multiple PDFs](https://help.syncfusion.com/file-formats/pdf/working-with-documents/merge-documents)** — Combine multiple PDF documents into a single file +- **[Split PDF Documents](https://help.syncfusion.com/file-formats/pdf/split-document)** — Extract specific pages from PDF files +- **[Add Watermarks](https://help.syncfusion.com/file-formats/pdf/working-with-pages/add-watermark)** — Add company logos or confidentiality markers +- **[Create Interactive Forms](https://help.syncfusion.com/file-formats/pdf/working-with-forms/overview)** — Build fillable PDF forms +- **[Digital Signatures](https://help.syncfusion.com/file-formats/pdf/working-with-forms/create-digital-signatures)** — Sign PDFs programmatically +- **[PDF Encryption](https://help.syncfusion.com/file-formats/pdf/working-with-security/encrypt-pdf)** — Protect PDFs with passwords + +### GCP App Engine Patterns +- **[Cloud Storage Integration](https://cloud.google.com/storage/docs)** — Store generated PDFs in Google Cloud Storage buckets +- **[Cloud Pub/Sub Event Processing](https://cloud.google.com/pubsub)** — Process PDF generation requests from message queues +- **[Cloud Datastore](https://cloud.google.com/datastore)** — Store PDF metadata and generation history +- **[Cloud CDN](https://cloud.google.com/cdn)** — Cache and deliver PDFs globally with low latency +- **[Scaling Configurations](https://cloud.google.com/appengine/docs/flexible/dotnet/configuring-your-app-with-app-yaml)** — Adjust `app.yaml` min/max instances and CPU thresholds +- **[Cloud Logging](https://cloud.google.com/logging)** — Monitor PDF generation performance and errors + +### Deployment and Operations +- **[Cloud Monitoring](https://cloud.google.com/monitoring)** — Set alerts for error rates, latency, memory usage +- **[Cloud Debugger](https://cloud.google.com/debugger)** — Debug PDF generation code in production +- **[Cloud Profiler](https://cloud.google.com/profiler)** — Identify performance bottlenecks in PDF operations +- **[Cloud Trace](https://cloud.google.com/trace)** — Analyze request latency and distributed tracing +- **[GCP Cost Management](https://cloud.google.com/cost-management)** — Monitor App Engine costs and set budget alerts +- **[CI/CD with Cloud Build](https://cloud.google.com/build)** — Automate testing and deployment on code commits + +## Resources + +**Sample Code:** +- [Complete GCP App Engine example](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/GCP/Google_App_Engine) + +**Documentation:** +- [Syncfusion .NET PDF Library Guide](https://help.syncfusion.com/file-formats/pdf/) +- [Google App Engine for .NET](https://cloud.google.com/appengine/docs/flexible/dotnet) +- [Deploying ASP.NET Core to App Engine](https://cloud.google.com/appengine/docs/flexible/dotnet/create-app) +- [Google Cloud SDK Documentation](https://cloud.google.com/sdk/docs) +- [Google Cloud Console](https://console.cloud.google.com/) — Manage your GCP resources +- [Cloud Shell Documentation](https://cloud.google.com/shell/docs) +- [Licensing Overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) + +**Try It Out:** +- [Syncfusion PDF Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) +- [Explore Syncfusion PDF Features](https://www.syncfusion.com/document-sdk/net-pdf-library) +- [GCP Free Tier](https://cloud.google.com/free) — $300 credit + always-free App Engine flexible quota (28 instance hours/day) +- [Cloud Shell](https://cloud.google.com/shell) — Browser-based terminal, no local installation needed -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Linux.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Linux.md index 40535d6173..ade489fa0e 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Linux.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Linux.md @@ -1,19 +1,31 @@ --- -title: Create PDF document on Linux | Syncfusion -description: Create PDF document in .NET Core application on Linux using Syncfusion .NET Core PDF library without the dependency of Adobe Acrobat. +title: Create a PDF File in Linux | Syncfusion +description: Create a PDF file in .NET Core application on Linux using Syncfusion .NET PDF library without the dependency of Adobe Acrobat. platform: document-processing control: PDF documentation: UG Keywords: linux os save pdf, linux os load pdf, c# save pdf, c# load pdf --- -# Create PDF document on Linux +# Create a PDF File in Linux The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents programmatically without the dependency on Adobe Acrobat. Using this library, you can create a PDF document in a .NET Core application on Linux. -## Steps to create PDF document programmatically +## Prerequisites -Step 1: Execute the following command in the Linux terminal to create a new .NET Core Console application project. +| Item | Details | +| --- | --- | +| **Operating System** | Linux (Ubuntu, Fedora, Debian, CentOS, etc.) | +| **.NET Version** | .NET 5.0 or later (.NET 6.0+ recommended) | +| **Development Environment** | Visual Studio Code, Visual Studio for Linux, or any text editor with .NET CLI | +| **.NET Core SDK** | Latest stable version | +| **NuGet Package** | Syncfusion.Pdf.NET (latest version) | +| **Additional Files** | Image file for the code sample (AdventureCycle.jpg) - place in project directory | +| **License** | Syncfusion license key (required for production use) | + +## Steps to create a PDF file programmatically + +**Step 1:** Execute the following command in the Linux terminal to create a new .NET Core Console application project. {% tabs %} {% highlight bash %} @@ -23,19 +35,28 @@ dotnet new console {% endhighlight %} {% endtabs %} -Step 2: Install the [Syncfusion.Pdf.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/) by executing the following command. +**Step 2:** Install the [Syncfusion.Pdf.Net.core](https://www.nuget.org/packages/Syncfusion.Pdf.NET) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/) by executing the following command. {% tabs %} {% highlight bash %} -dotnet add package Syncfusion.Pdf.Net.Core -v xx.x.x.xx -s https://www.nuget.org/ +dotnet add package Syncfusion.Pdf.Net.Core -s https://www.nuget.org/ {% endhighlight %} {% endtabs %} -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from the trial setup or from the NuGet feed, you also have to add the "Syncfusion.Licensing" assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to know about registering the Syncfusion® license key in your application to use our components. +**Step 3:** Register the Syncfusion license key in the *Program.cs* file before creating any Syncfusion objects. This is required for production use. Refer to the [Syncfusion licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for detailed instructions on registering your license key. + +{% tabs %} +{% highlight c# tabtitle="C#" %} + +// Register Syncfusion license +Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + +{% endhighlight %} +{% endtabs %} -Step 3: Include the following namespaces in the *Program.cs* file. +**Step 4:** Include the following namespaces in the *Program.cs* file. {% tabs %} {% highlight c# tabtitle="C#" %} @@ -48,66 +69,72 @@ using System.IO; {% endhighlight %} {% endtabs %} -Step 4: Add the following code sample to the *Program.cs* file to **create a PDF document in the .NET Core application on Linux**. +**Step 5:** Add the following code sample to the *Program.cs* file to create a PDF file in the .NET Core application on Linux. {% tabs %} {% highlight c# tabtitle="C#" %} -//Create a new PDF document. -PdfDocument document = new PdfDocument(); -// Set the page size. -document.PageSettings.Size = PdfPageSize.A4; -//Add a page to the document. -PdfPage page = document.Pages.Add(); - -//Create PDF graphics for the page. -PdfGraphics graphics = page.Graphics; -//Load the image from the disk. -FileStream imageStream = new FileStream("AdventureCycle.jpg", FileMode.Open, FileAccess.Read); -PdfBitmap image = new PdfBitmap(imageStream); -//Draw an image. -graphics.DrawImage(image, new RectangleF(130,0, 250, 100)); - -//Draw header text. -graphics.DrawString("Adventure Works Cycles", new PdfStandardFont(PdfFontFamily.TimesRoman, 20, PdfFontStyle.Bold), PdfBrushes.Gray, new PointF(150, 150)); - -//Add paragraph. -string text = "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sel -//Create a text element with the text and font. -PdfTextElement textElement = new PdfTextElement(text, new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); -//Draw the text in the first column. -textElement.Draw(page, new RectangleF(0, 200, page.GetClientSize().Width, page.GetClientSize().Height)); - -//Create a PdfGrid. -PdfGrid pdfGrid = new PdfGrid(); -//Add values to the list. -List data = new List(); -Object row1 = new { Product_ID = "1001", Product_Name = "Bicycle", Price = "10,000" }; -Object row2 = new { Product_ID = "1002", Product_Name = "Head Light", Price = "3,000" }; -Object row3 = new { Product_ID = "1003", Product_Name = "Break wire", Price = "1,500" }; -data.Add(row1); -data.Add(row2); -data.Add(row3); -//Add list to IEnumerable. -IEnumerable dataTable = data; -//Assign data source. -pdfGrid.DataSource = dataTable; -//Apply built-in table style. -pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); -//Draw the grid to the page of PDF document. -pdfGrid.Draw(graphics, new RectangleF(0, 300, page.Size.Width - 80, 0)); - -//Create file stream. -using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output.pdf"), FileMode.Create, FileAccess.ReadWrite)) +try { - //Save the PDF document to file stream. - document.Save(outputFileStream); + // Create a new PDF document + using (PdfDocument document = new PdfDocument()) + { + // Set the page size + document.PageSettings.Size = PdfPageSize.A4; + // Add a page to the document + PdfPage page = document.Pages.Add(); + + // Create PDF graphics for the page + PdfGraphics graphics = page.Graphics; + + // Load and draw image from disk + using (FileStream imageStream = new FileStream("AdventureCycle.jpg", FileMode.Open, FileAccess.Read)) + { + PdfBitmap image = new PdfBitmap(imageStream); + graphics.DrawImage(image, new RectangleF(130, 0, 250, 100)); + } + + // Draw header text + graphics.DrawString("Adventure Works Cycles", new PdfStandardFont(PdfFontFamily.TimesRoman, 20, PdfFontStyle.Bold), PdfBrushes.Gray, new PointF(150, 150)); + + // Add paragraph + string text = "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal bicycles to North American markets and expands its market to other regions."; + PdfTextElement textElement = new PdfTextElement(text, new PdfStandardFont(PdfFontFamily.TimesRoman, 12)); + textElement.Draw(page, new RectangleF(0, 200, page.GetClientSize().Width, page.GetClientSize().Height)); + + // Create a grid with product data + PdfGrid pdfGrid = new PdfGrid(); + List data = new List(); + data.Add(new { Product_ID = "1001", Product_Name = "Bicycle", Price = "10,000" }); + data.Add(new { Product_ID = "1002", Product_Name = "Head Light", Price = "3,000" }); + data.Add(new { Product_ID = "1003", Product_Name = "Brake Wire", Price = "1,500" }); + + // Assign data source and style + pdfGrid.DataSource = data; + pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent3); + + // Draw the grid on the page + pdfGrid.Draw(graphics, new RectangleF(0, 300, page.Size.Width - 80, 0)); + + // Save the PDF document to file + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "Output.pdf"); + using (FileStream outputFileStream = new FileStream(outputPath, FileMode.Create, FileAccess.ReadWrite)) + { + document.Save(outputFileStream); + } + + Console.WriteLine($"PDF created successfully at: {outputPath}"); + } +} +catch (Exception ex) +{ + Console.WriteLine($"Error creating PDF: {ex.Message}"); } {% endhighlight %} {% endtabs %} -Step 5: Execute the following command to restore the NuGet packages. +**Step 6:** Execute the following command to restore the NuGet packages. {% tabs %} {% highlight bash %} @@ -117,9 +144,8 @@ dotnet restore {% endhighlight %} {% endtabs %} -![Linux Build](GettingStarted_images/Linux_Build.png) +**Step 7:** Execute the following command in the terminal to build and run the application. -Step 6: Execute the following command in terminal to run the application. {% tabs %} {% highlight bash %} @@ -128,11 +154,41 @@ dotnet run {% endhighlight %} {% endtabs %} -![Linux Run](GettingStarted_images/Linux_Run.png) +Upon successful execution, the console will display the file path where the PDF has been created. The output PDF file (`Output.pdf`) will be saved in the current working directory (same location as Program.cs). + +## Output + +The executed program generates a PDF document with: +- Header text: "Adventure Works Cycles" +- Sample product image +- Paragraph description +- Product data table with sample items + +A complete working example can be downloaded from the [GitHub repository](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Linux). + +## Troubleshooting + +| Issue | Solution | +| --- | --- | +| "AdventureCycle.jpg not found" | Ensure the image file exists in the project directory or provide the full path to the image file | +| "System.IO.FileNotFoundException" on image load | Verify file permissions and that the working directory is set correctly | +| "License key is missing" | Register your Syncfusion license key in Step 3 before creating PDF objects | +| PDF file not created | Check that the directory has write permissions and sufficient disk space | +| Font rendering issues on Linux | Install additional fonts: `sudo apt-get install fonts-dejavu fonts-liberation` (Ubuntu/Debian) | +| "Syncfusion.Licensing" not found | Ensure Syncfusion.Pdf.NET NuGet package is installed correctly | +| Application exits silently | Check the console output for error messages; ensure all required files are accessible | +| Broken links or missing images in PDF | Verify that file paths are correct and use absolute paths or Path.GetFullPath() | + +## Next Steps -A complete working sample can be downloaded from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Linux). +Explore advanced features and capabilities with the Syncfusion .NET PDF library: -By executing the program, you will get the PDF document as follows. The output will be saved alongside Program.cs. -![Linux output PDF document](GettingStarted_images/Open_and_save_output.png) +- [Merge PDF Documents](./merge-pdf-documents.md) - Combine multiple PDF files into one +- [Split PDF Documents](./split-pdf-documents.md) - Extract or divide PDF pages +- [Add Watermarks](./add-watermark.md) - Apply text and image watermarks +- [Work with Forms](./fill-form-fields.md) - Create and fill interactive PDF forms +- [Add Digital Signatures](./digital-signatures.md) - Sign PDFs digitally +- [Secure Documents](./encrypt-pdf.md) - Encrypt and password-protect PDFs +- [Other Platforms](../../getting-started.md) - PDF generation guides for .NET Framework, ASP.NET Core, WPF, Windows Forms, and more -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. \ No newline at end of file +For additional examples and comprehensive API documentation, visit the [Syncfusion .NET PDF documentation](https://help.syncfusion.com/document-processing/pdf/overview). \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-MaUI.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-MaUI.md index 0ed101d837..07b4d96647 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-MaUI.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-MaUI.md @@ -1,19 +1,68 @@ --- -title: Create or Generate PDF file in MAUI | Syncfusion -description: Learn how to create or generate a PDF file in .NET MAUI with easy steps using Syncfusion .NET Core PDF library without depending on Adobe. +title: Create a PDF File in .NET MAUI | Syncfusion +description: Learn how to create a PDF file in .NET MAUI with easy steps using Syncfusion .NET PDF library without depending on Adobe. platform: document-processing control: PDF documentation: UG --- -# Create PDF file in .NET MAUI +# Create a PDF File in .NET MAUI The [.NET MAUI PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit **PDF** documents. This library also includes functions for merging, splitting, stamping, working with forms, and securing PDF files and more. Using this library, you can create a PDF document in a .NET MAUI application. N> Our PDF library is currently supported in .NET MAUI applications on Android, iOS, and Windows platforms. It is not supported on the Mac Catalyst platform. +## Prerequisites + +| Category | Requirement | +|---|---| +| **IDE** | Visual Studio 2022 or later, Visual Studio Code, or JetBrains Rider | +| **.NET Framework** | .NET 6.0 or later | +| **MAUI Version** | .NET MAUI 6.0 or later | +| **Platform SDKs** | Android API 21+, iOS 11.0+, Windows 10 Build 19041+ | +| **NuGet Package** | Syncfusion.Pdf.NET (latest stable version) | +| **License** | Syncfusion license (required for production use) | + ## Steps to create PDF document programmatically in .NET MAUI +### Step 1: Register the Syncfusion License + +The Syncfusion PDF library requires a license to function in production environments. Register the license by adding the following code in your **MauiProgram.cs** file: + +```csharp +using Syncfusion.Licensing; + +public static class MauiProgram +{ + public static MauiApp CreateMauiApp() + { + // Register Syncfusion license + SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + + var builder = MauiApp.CreateBuilder(); + return builder + .UseMauiApp() + .ConfigureFonts(fonts => + { + fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); + }) + .Build(); + } +} +``` + +Replace `YOUR_LICENSE_KEY` with your actual Syncfusion license key. + +### Step 2: Install the NuGet Package + +Add the Syncfusion PDF NuGet package to your .NET MAUI project: + +```bash +dotnet add package Syncfusion.Pdf.NET +``` + +### Step 3: Create PDF Document Programmatically + {% tabcontents %} {% tabcontent Visual Studio %} {% include_relative tabcontent-support/Create-PDF-document-in-MaUI-Visual-Studio.md %} @@ -24,7 +73,7 @@ N> Our PDF library is currently supported in .NET MAUI applications on Android, {% endtabcontent %} {% tabcontent JetBrains Rider %} -{% include_relative tabcontent-support/Create-PDF-document-in-Blazor-MaUI-JetBrains.md %} +{% include_relative tabcontent-support/Create-PDF-document-in-MaUI-JetBrains.md %} {% endtabcontent %} {% endtabcontents %} @@ -41,6 +90,19 @@ By executing the program on iOS, you will get the PDF document as follows. N> You can also explore our [MAUI PDF library demo](https://www.syncfusion.com/demos/fileformats/pdf-library) that shows how to create and modify PDF files from C# with just five lines of code. +## Troubleshooting + +| Issue | Cause | Solution | +|---|---|---| +| **NuGet package not found** | Package not installed or source not configured | Run `dotnet add package Syncfusion.Pdf.NET` and verify NuGet source | +| **License registration fails** | Invalid or missing license key | Verify license key in MauiProgram.cs; check [Syncfusion Account](https://www.syncfusion.com/account/manage-licenses) | +| **PDF not saved on Android** | Missing file permissions | Add `` to AndroidManifest.xml | +| **File access denied** | Insufficient folder permissions | Use SaveService helpers from downloaded package to handle platform-specific paths | +| **SaveService.SaveAndDisplay() not found** | Helper files not added to project | Download helper files from the link below and add to project | +| **Platform-specific errors** | Incomplete platform SDK installation | Ensure Android API 21+, iOS 11.0+, and Windows 10 Build 19041+ are installed | +| **Using statement not recognized** | Missing namespace import | Add `using Syncfusion.Pdf;` at top of file | +| **File opens but appears blank** | PDF content not written before save | Ensure graphics operations complete before document.Save() | + **Helper files for .NET MAUI** Download the helper files from this [link](https://www.syncfusion.com/downloads/support/directtrac/general/ze/Helper_files-1664336865) and add them into the mentioned project. These helper files allow you to save the stream as a physical file and open the file for viewing. @@ -64,7 +126,7 @@ Download the helper files from this [link](https://www.syncfusion.com/downloads/ SaveService.cs - Represent the base class for save operation. + Represents the base class for save operation. @@ -88,16 +150,6 @@ Download the helper files from this [link](https://www.syncfusion.com/downloads/ - - Mac Catalyst - - - SaveMac.cs - - Save implementation for Mac Catalyst device. - - - iOS @@ -120,4 +172,13 @@ Download the helper files from this [link](https://www.syncfusion.com/downloads/ Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). + +## Next Steps + +- **[Merge PDF files](https://help.syncfusion.com/document-processing/pdf-library/net/merge-pdf-files)** — Combine multiple PDF documents into a single file +- **[Split PDF files](https://help.syncfusion.com/document-processing/pdf-library/net/split-pdf-files)** — Divide a PDF into separate documents +- **[Add watermark to PDF](https://help.syncfusion.com/document-processing/pdf-library/net/add-watermark)** — Stamp text or images on PDF pages +- **[Work with PDF forms](https://help.syncfusion.com/document-processing/pdf-library/net/working-with-forms)** — Fill and flatten interactive form fields +- **[Secure PDF documents](https://help.syncfusion.com/document-processing/pdf-library/net/securing-pdf-documents)** — Add encryption and permissions to PDFs +- **[Explore other .NET platforms](https://help.syncfusion.com/document-processing/pdf-library/net)** — Create PDFs in WPF, WinForms, UWP, WinUI, Blazor, and more \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Mac-OS.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Mac-OS.md index 1c47101e87..5f6499d0ff 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Mac-OS.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Mac-OS.md @@ -1,33 +1,83 @@ --- -title: Create PDF document on Mac OS | Syncfusion -description: Create PDF document in ASP.NET Core application on Mac OS using Syncfusion .NET Core PDF library without the dependency of Adobe Acrobat. +title: Create a PDF File in macOS | Syncfusion +description: Create a PDF file in .NET Core application on macOS using Syncfusion .NET PDF library without the dependency of Adobe Acrobat. platform: document-processing control: PDF documentation: UG -keywords: mac os save pdf, mac os load pdf, c# save pdf, c# load pdf +keywords: macos save pdf, macos load pdf, c# save pdf, c# load pdf --- -# Create PDF document on macOS +# Create a PDF File in macOS -The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents programmatically without the dependency on Adobe Acrobat. Using this library, you can create a PDF document on macOS. +The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents programmatically without the dependency on Adobe Acrobat. Using this library, you can create a PDF file in a .NET Core application on macOS. -## Steps to create PDF document programmatically in .NET Core application on macOS +## Prerequisites + +| Item | Details | +| --- | --- | +| **Operating System** | macOS 10.15 or later | +| **.NET Version** | .NET 5.0 or later (.NET 6.0+ recommended) | +| **Development Environment** | Visual Studio 2022 for Mac, Visual Studio Code with C# extension, or any text editor with .NET CLI | +| **.NET Core SDK** | Latest stable version | +| **NuGet Package** | Syncfusion.Pdf.NET (latest version) | +| **License** | Syncfusion license key (required for production use) | + +## Steps to create a PDF file in .NET Core on macOS + +Select your preferred development environment below: + +### Visual Studio 2022 for Mac -{% tabcontents %} -{% tabcontent Visual Studio %} {% include_relative tabcontent-support/Create-PDF-document-in-Mac-OS-Visual-Studio.md %} -{% endtabcontent %} - -{% tabcontent Visual Studio Code %} + +### Visual Studio Code + {% include_relative tabcontent-support/Create-PDF-document-in-Mac-OS-VS-Code.md %} -{% endtabcontent %} -{% endtabcontents %} -A complete working sample can be downloaded from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Mac). +## License Registration + +Starting with v16.2.0.x, Syncfusion assemblies require a license key. Refer to the [Syncfusion licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview) for detailed instructions on registering your license key in your application. + +## Output + +Upon successful execution, your application will generate a PDF file containing: +- Header text and title information +- Sample product images (if image file is provided) +- Formatted text and paragraphs +- Data grid with sample product information +- Professional styling using built-in table styles + +The output PDF file will be saved in the current working directory with the filename specified in your code (typically `Output.pdf`). + +A complete working sample can be downloaded from the [GitHub repository](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Mac). -By executing the program, you will get the PDF document as follows. ![macOS output PDF document](GettingStarted_images/Open_and_save_output.png) -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +## Troubleshooting + +| Issue | Solution | +| --- | --- | +| "Image file not found" error | Ensure the image file (e.g., AdventureCycle.jpg) exists in the project directory or provide the full file path | +| "System.IO.FileNotFoundException" | Check file permissions and verify working directory is set correctly | +| "License key is missing" or "License key expired" | Register your Syncfusion license key in Program.cs before creating PDF objects | +| PDF file not created | Verify that the output directory has write permissions and sufficient disk space is available | +| Font rendering issues on macOS | Some fonts may not be available; use standard fonts (TimesRoman, Helvetica, Courier) for better compatibility | +| "Syncfusion.Licensing" assembly not found | Ensure the Syncfusion.Pdf.NET NuGet package is installed correctly: `dotnet add package Syncfusion.Pdf.NET` | +| Application crashes or hangs | Check console output for error messages; ensure all file paths are accessible and resources are properly disposed | +| Broken image links in generated PDF | Verify image file paths are correct and use absolute paths or Path.GetFullPath() for reliability | + +## Next Steps + +Explore advanced features and capabilities with the Syncfusion .NET PDF library: + +- [Merge PDF Documents](./merge-pdf-documents.md) - Combine multiple PDF files into one +- [Split PDF Documents](./split-pdf-documents.md) - Extract or divide PDF pages +- [Add Watermarks](./add-watermark.md) - Apply text and image watermarks to PDFs +- [Work with Forms](./fill-form-fields.md) - Create and fill interactive PDF forms +- [Add Digital Signatures](./digital-signatures.md) - Sign PDFs digitally +- [Secure Documents](./encrypt-pdf.md) - Encrypt and password-protect PDFs +- [Other Platforms](../../getting-started.md) - PDF generation guides for other platforms and environments + +For additional examples and comprehensive API documentation, visit the [Syncfusion .NET PDF documentation](https://help.syncfusion.com/document-processing/pdf/overview). -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +You can also explore our [interactive PDF demo](https://document.syncfusion.com/demos/pdf/default#/tailwind) to see the library in action. \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-UWP.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-UWP.md index 118a446f19..dc27a624ff 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-UWP.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-UWP.md @@ -6,34 +6,76 @@ control: PDF documentation: UG --- -# Create or Generate PDF file in UWP +# Create a PDF File in UWP The [UWP PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, work with forms, and secure PDF files. -To include the Syncfusion® UWP PDF library into your UWP application, please refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. +## Prerequisites -## Steps to create PDF document in UWP +| Requirement | Version | +|-------------|---------| +| Visual Studio | 2019 or later (2022 recommended) | +| .NET Framework | 4.5+ or .NET Core 3.1+ | +| Windows SDK | 10.0.17763.0+ | +| Syncfusion PDF NuGet Package | [Syncfusion.Pdf.UWP](https://www.nuget.org/packages/Syncfusion.Pdf.UWP/) (latest) | +| Project Type | UWP (Universal Windows Platform) | -Step 1: Create a new UWP application project. +To include the Syncfusion® UWP PDF library into your UWP application, refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. + +## Steps to create a PDF document in UWP + +### Step 1: Create a new UWP application project ![UWP sample creation](GettingStarted_images/UWP_sample_creation.png) -Step 2: Install the [Syncfusion.Pdf.UWP](https://www.nuget.org/packages/Syncfusion.Pdf.UWP/) NuGet package as a reference to your UWP applications from [NuGet.org](https://www.nuget.org/). +Open Visual Studio and create a new **Blank App (Universal Windows)** project for your target platform. + +### Step 2: Install the Syncfusion.Pdf.UWP NuGet package + +Install the [Syncfusion.Pdf.UWP](https://www.nuget.org/packages/Syncfusion.Pdf.UWP/) NuGet package as a reference to your UWP application from [NuGet.org](https://www.nuget.org/). + ![PDF UWP Nuget package](GettingStarted_images/NuGet-package-UWP.png) -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add the `Syncfusion.Licensing` assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to learn about registering the Syncfusion® license key in your application to use our components. +You can also install via Package Manager Console: +```powershell +Install-Package Syncfusion.Pdf.UWP +``` + +### Step 3: Register Syncfusion license + +Starting with v16.2.0.x, you must register a Syncfusion license key to use the library. Add the license key in your **App.xaml.cs** file before using any PDF functionality: + +```csharp +using Syncfusion.Licensing; + +public partial class App : Application +{ + public App() + { + this.InitializeComponent(); + // Register Syncfusion license + SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + } +} +``` + +Refer to [Licensing Overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) for license registration details. + +### Step 4: Create the UI with a button -Step 3: Create button in *MainPage.Xaml* page using below code example and create *Button_Click* event. +Create a button in **MainPage.xaml** using the code below and add a `Button_Click` event handler: {% tabs %} {% highlight XAML %} - + {% endhighlight %} {% endtabs %} -Step 6: Include the following namespaces in the **MainWindow.xaml.cs** file. +### Step 5: Add required namespaces + +Include the following namespaces in the **MainWindow.xaml.cs** file: {% tabs %} {% highlight c# tabtitle="C#" %} using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; -using Syncfusion.Pdf.Grid; using Syncfusion.Drawing; -using System.Reflection; -using System.Xml.Linq; +using System; +using System.IO; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; {% endhighlight %} {% endtabs %} -Step 7: Add a new action method *createPdf_Click* in *MainWindow.xaml.cs* and include the below code example to generate a PDF document using the [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) class. The [PdfTextElement](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfTextElement.html) is used to add text to a PDF document and provides layout results that help prevent content overlapping. Load image stream from the local files on disk and draw the images through the [DrawImage](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawImage_Syncfusion_Pdf_Graphics_PdfImage_System_Single_System_Single_) method of the [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html) class. The [PdfGrid](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Grid.PdfGrid.html) allows you to create a table by entering data manually or from external data sources and include helper classes, methods and required files in the assets folder. +### Step 6: Implement basic PDF generation + +Add the following code to the **MainWindow.xaml.cs** code-behind to create the `OnGenerateButtonClick` event handler. This generates a simple PDF document using the [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) class. The [DrawString](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html) method of [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html) draws text on the page. The `PointF(0, 0)` parameter specifies the starting position (top-left corner) in points (1/72 inch). {% tabs %} {% highlight c# tabtitle="C#" %} -private void CreatePdf_Click(object sender, RoutedEventArgs e) +private void OnGenerateButtonClick(object sender, RoutedEventArgs e) { //Create a new PDF document. PdfDocument document = new PdfDocument(); @@ -221,13 +270,33 @@ private void CreatePdf_Click(object sender, RoutedEventArgs e) {% endhighlight %} {% endtabs %} -A complete working example of creating a PDF document in the WinUI Desktop app can be downloaded from this [link](https://www.syncfusion.com/downloads/support/directtrac/general/ze/CreatePdfDemoSample208256365). +### Step 7: Build and run the application -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/WinUI). +1. Build the WinUI application (Build > Build Solution) +2. Run the application (Debug > Start Debugging or F5) +3. Click the **Generate PDF** button +4. The PDF will be created in your Documents folder and the success dialog will display the file location -By executing the program, you will get the PDF document as follows. -![Output PDF image](WinUI_Images/GettingStartedOutput.png) +**Expected output:** A file named `Output.pdf` containing "Hello World!!!" text. -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +![Output PDF image](WinUI_Images/GettingStartedOutput.png) -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| "The type or namespace 'Syncfusion' could not be found" | Verify Syncfusion.Pdf.NET NuGet package is installed; restore NuGet packages (Tools > Manage NuGet Packages for Solution) | +| "License key not registered" error at runtime | Register license in App.xaml.cs using SyncfusionLicenseProvider.RegisterLicense() before creating any PDF objects | +| "Access to the path is denied" when saving | Verify Documents folder exists and has write permissions; check that app has file system access capability | +| "File not found" after generation | Verify the Documents folder exists; check that the path is accessible; use Environment.SpecialFolder for reliable path handling | +| "ContentDialog not initialized" error | Ensure XamlRoot is set on dialog; verify dialog is created after UI is loaded | +| Application crashes when button is clicked | Add try-catch error handling; verify all required using statements are included; check that license is registered | +| PDF doesn't open after creation | Install a PDF reader (Windows Reader, Adobe Reader, etc.); verify file was created successfully before attempting to open | +| "PointF not found" error | Ensure `using Syncfusion.Drawing;` is included in namespaces | + +## Next Steps + +- **Download [Complete Working Sample](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/WinUI)** — Reference implementation with error handling and best practices +- **Try [Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind)** — Interactive examples and feature showcase +- **Explore [PDF Library Features](https://www.syncfusion.com/document-sdk/net-pdf-library)** — Comprehensive API reference including tables, images, forms, and security features +- **View [API Documentation](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html)** — Full class and method reference for PdfDocument and related classes \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Windows-Forms.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Windows-Forms.md index 62904344ea..66b4770e31 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Windows-Forms.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Windows-Forms.md @@ -6,35 +6,86 @@ control: PDF documentation: UG --- -# Create or Generate PDF file in Windows Forms +# Create a PDF File in Windows Forms The [.NET PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, work with forms, and secure PDF files. -To include the .NET PDF library into your Windows Forms application, please refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. +## Prerequisites -## Steps to create PDF document in Windows Forms +| Requirement | Version | +|-------------|---------| +| Visual Studio | 2019 or later (2022 recommended) | +| .NET Framework | 4.5+ or .NET 5+ | +| Syncfusion PDF NuGet Package | [Syncfusion.Pdf.WinForms](https://www.nuget.org/packages/Syncfusion.Pdf.WinForms/) (latest) | +| Project Type | Windows Forms Application (.NET Framework or .NET Core) | + +To include the .NET PDF library into your Windows Forms application, refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. + +## Steps to create a PDF document in Windows Forms + +### Step 1: Create a new Windows Forms application project + +Create a new **Windows Forms Application** project in Visual Studio. -Step 1: Create a new Windows Forms application project. ![Windows Forms sample creation](GettingStarted_images/WF-sample-creation.png) -Step 2: Install the [Syncfusion.Pdf.WinForms](https://www.nuget.org/packages/Syncfusion.Pdf.WinForms/) NuGet package as a reference to your .NET Framework applications from [NuGet.org](https://www.nuget.org/). +### Step 2: Install the Syncfusion.Pdf.WinForms NuGet package + +Install the [Syncfusion.Pdf.WinForms](https://www.nuget.org/packages/Syncfusion.Pdf.WinForms/) NuGet package as a reference to your Windows Forms application from [NuGet.org](https://www.nuget.org/). + ![Windows Forms PDF NuGet package](GettingStarted_images/WF-NuGet-package.png) -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add the `Syncfusion.Licensing` assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to learn about registering the Syncfusion® license key in your application to use our components. +You can also install via Package Manager Console: + +```powershell +Install-Package Syncfusion.Pdf.WinForms +``` + +### Step 3: Register Syncfusion license + +Starting with v16.2.0.x, you must register a Syncfusion license key to use the library. Add the license key in your **Program.cs** file before creating the application form: + +```csharp +using Syncfusion.Licensing; -Step 3: Include the following namespaces in the *Form1.Designer.cs* file. +static class Program +{ + [STAThread] + static void Main() + { + // Register Syncfusion license + SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY"); + + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } +} +``` + +Refer to [Licensing Overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) for license registration details. + +### Step 4: Add required namespaces + +Include the following namespaces in the **Form1.cs** file (code-behind, not Designer.cs): {% tabs %} {% highlight c# tabtitle="C#" %} using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; +using System; +using System.Diagnostics; using System.Drawing; +using System.IO; +using System.Windows.Forms; {% endhighlight %} {% endtabs %} -Step 4: Add a new button in *Form1.Designer.cs* to create PDF document as follows. +### Step 5: Create the UI with a button + +Add a button and label in the **Form1.Designer.cs** InitializeComponent() method to create the PDF document UI: {% tabs %} {% highlight c# tabtitle="C#" %} @@ -57,7 +108,7 @@ private void InitializeComponent() btnCreate.Location = new System.Drawing.Point(180, 110); btnCreate.Size = new System.Drawing.Size(85, 26); btnCreate.Text = "Create PDF"; - btnCreate.Click += new EventHandler(btnCreate_Click); + btnCreate.Click += new EventHandler(OnGenerateButtonClick); //Create PDF ClientSize = new System.Drawing.Size(450, 150); @@ -69,12 +120,14 @@ private void InitializeComponent() {% endhighlight %} {% endtabs %} -Step 5: Create the btnCreate_Click event and add the below code sample in btnCreate_Click to generate a PDF document using the [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) class. Then use the [DrawString](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawString_System_String_Syncfusion_Pdf_Graphics_PdfFont_Syncfusion_Pdf_Graphics_PdfBrush_System_Drawing_PointF_) method of the [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html) object to draw the text on the PDF page. +### Step 6: Implement PDF generation + +Add the following code to the **Form1.cs** code-behind to create the `OnGenerateButtonClick` event handler. This generates a PDF document using the [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) class. The [DrawString](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawString_System_String_Syncfusion_Pdf_Graphics_PdfFont_Syncfusion_Pdf_Graphics_PdfBrush_System_Drawing_PointF_) method of [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html) draws text on the page. The `PointF(0, 0)` parameter specifies the starting position (top-left corner) in points (1/72 inch). {% tabs %} {% highlight c# tabtitle="C#" %} -private void GeneratePDF(object sender, EventArgs e) +private void OnGenerateButtonClick(object sender, EventArgs e) { //Create a new PDF document. using (PdfDocument document = new PdfDocument()) @@ -95,11 +148,33 @@ private void GeneratePDF(object sender, EventArgs e) {% endhighlight %} {% endtabs %} -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Windows%20Forms/Create-new-PDF-document). +### Step 7: Build and run the application -By executing the program, you will get the PDF document as follows. -![WF output PDF document](GettingStarted_images/pdf-generation-output.png) +1. Build the Windows Forms application (Build > Build Solution) +2. Run the application (Debug > Start Debugging or F5) +3. Click the **Generate PDF** button +4. The PDF will be created in your Documents folder and automatically open -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +**Expected output:** A file named `Output.pdf` containing "Hello World!!!" text. + +![WF output PDF document](GettingStarted_images/pdf-generation-output.png) -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| "The type or namespace 'Syncfusion' could not be found" | Verify Syncfusion.Pdf.WinForms NuGet package is installed; restore NuGet packages (Tools > Manage NuGet Packages for Solution) | +| "License key not registered" error at runtime | Register license in Program.cs using SyncfusionLicenseProvider.RegisterLicense() before creating the form | +| "Access to the path is denied" when saving | Verify the Documents folder has write permissions; ensure app runs with sufficient privileges | +| "File not found" after generation | Verify the Documents folder exists; use full absolute path or Environment.SpecialFolder for reliability | +| PDF doesn't open automatically | Install a PDF reader (Adobe Reader, Windows Reader, etc.); verify file was created successfully first | +| Application crashes when button is clicked | Add try-catch error handling; verify all required using statements are included; check license registration | +| "PointF not found" error | Ensure `using System.Drawing;` is included in namespaces | +| Event handler not firing | Verify event handler name matches in InitializeComponent() (check spelling and case sensitivity) | + +## Next Steps + +- **Download [Complete Working Sample](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Windows%20Forms/Create-new-PDF-document)** — Reference implementation with error handling and best practices +- **Try [Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind)** — Interactive examples and feature showcase +- **Explore [PDF Library Features](https://www.syncfusion.com/document-sdk/net-pdf-library)** — Comprehensive API reference including tables, images, forms, and security features +- **View [API Documentation](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html)** — Full class and method reference for PdfDocument and related classes \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Xamarin.md b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Xamarin.md index f6743262fc..cf5a5c6d8e 100644 --- a/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Xamarin.md +++ b/Document-Processing/PDF/PDF-Library/NET/Create-PDF-file-in-Xamarin.md @@ -1,37 +1,65 @@ --- -title: Create or Generate PDF file in Xamarin | Syncfusion -description: Learn how to create or generate a PDF file in Xamarin with easy steps using Syncfusion Xamarin PDF library without depending on Adobe. +title: Create a PDF File in Xamarin | Syncfusion +description: Learn how to create a PDF file in Xamarin with easy steps using Syncfusion Xamarin PDF library without depending on Adobe. platform: document-processing control: PDF documentation: UG --- -# Create or Generate PDF file in Xamarin +# Create a PDF File in Xamarin -The [Xamarin PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, work with forms, and secure PDF files. +> **⚠️ Deprecation Notice:** Xamarin is deprecated as of May 2024. For new projects, use [.NET MAUI](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/create-pdf-document-in-blazor), which provides better performance and cross-platform support. + +The [Xamarin PDF library](https://www.syncfusion.com/document-sdk/net-pdf-library) enables you to create, read, and edit PDF documents. It provides advanced features including merging, splitting, stamping documents, managing forms, and securing PDF files with encryption. + +**Requirements:** +- Xamarin.Forms 5.0 or later (4.0+ supported) +- Visual Studio 2019 or later +- .NET Standard 2.0+ To include the Syncfusion® Xamarin PDF library into your Xamarin application, please refer to the [NuGet Package Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/nuget-packages-required) or [Assemblies Required](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/assemblies-required) documentation. -## Steps to create PDF document in Xamarin +## Project Setup -Step 1: Create a new C# Xamarin.Forms application project. +### Step 1: Create a new C# Xamarin.Forms application project ![Xamarin project creation](Xamarin_images/Xamarin_project_creation.jpg) -Step 2: Select a project template and required platforms to deploy the application. In this application, the portable assemblies to be shared across multiple platforms, so the .NET Standard code sharing strategy has been selected. For more details about code sharing, refer [here](https://learn.microsoft.com/en-us/xamarin/cross-platform/app-fundamentals/code-sharing). +### Step 2: Select project template and code sharing strategy + +Select a project template and target platforms (iOS, Android, UWP, etc.). For code sharing, choose **one of the following:** + +- **.NET Standard (Recommended):** For new projects using shared portable assemblies across all platforms +- **Portable Class Library (PCL):** Legacy option for older Xamarin projects -N> If .NET Standard is not available in the code sharing strategy, the Portable Class Library (PCL) can be selected. +For more details about code sharing strategies, refer to the [Xamarin documentation](https://learn.microsoft.com/en-us/xamarin/cross-platform/app-fundamentals/code-sharing). ![Xamarin project creation step2](Xamarin_images/Select_blank_app.jpg) -Step 3: Install the [Syncfusion.Xamarin.PDF](https://www.nuget.org/packages/Syncfusion.Xamarin.PDF/) NuGet package as a reference to your Xamarin.Forms applications from [NuGet.org](https://www.nuget.org/). +### Step 3: Install the Syncfusion PDF NuGet package + +Install the [Syncfusion.Xamarin.PDF](https://www.nuget.org/packages/Syncfusion.Xamarin.PDF/) NuGet package to your portable project from [NuGet.org](https://www.nuget.org/). + ![Install Xamarin PDF NuGet package](Xamarin_images/NuGet_package.jpg) -N> Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add the `Syncfusion.Licensing` assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to learn about registering the Syncfusion® license key in your application to use our components. +**Via Package Manager Console:** +``` +Install-Package Syncfusion.Xamarin.PDF +``` + +### Step 3a: Configure Licensing (Required) + +Starting with v16.2.0.x and later, you must register a Syncfusion license key to use the components. Add the `Syncfusion.Licensing` NuGet package and register your license key. Refer to the [licensing overview](https://help.syncfusion.com/common/essential-studio/licensing/overview) for step-by-step instructions. -Step 4: Add new Forms XAML page in portable project if there is no XAML page is defined in the App class. Otherwise, proceed to the next step. +N> Without a valid license key, your application will throw licensing errors at runtime. -a. To add the new XAML page, right-click the project and select **Add > New Item** and add a Forms XAML Page from the list. Name it as **MainXamlPage**. +## Create the User Interface -b. In App class of portable project (App.cs), replace the existing constructor of App class with the following code example, which invokes the *MainXamlPage*. +### Step 4: Add a XAML page (if not already defined) + +If no XAML page is already defined in the App class, add a new Forms XAML page: + +a. Right-click the portable project and select **Add > New Item**. Choose **Forms XAML Page** and name it `MainXamlPage`. + +b. In the `App.cs` file (portable project), replace the App constructor to set `MainXamlPage` as the root page: {% tabs %} {% highlight c# tabtitle="C#" %} @@ -45,7 +73,9 @@ public App() {% endhighlight %} {% endtabs %} -Step 5: In the *MainXamlPage.xaml*, add new button as follows. +### Step 5: Add a button to trigger PDF generation + +In `MainXamlPage.xaml`, add a button that will generate the PDF document: {% tabs %} {% highlight XAML %} @@ -59,96 +89,126 @@ Step 5: In the *MainXamlPage.xaml*, add new button as follows. {% endhighlight %} {% endtabs %} -Step 6: Include the following namespace in the *MainXamlPage.xaml.cs* file. +## Implement PDF Generation + +### Step 6: Add required namespaces + +Add the following namespaces to `MainXamlPage.xaml.cs`: {% tabs %} {% highlight c# tabtitle="C#" %} using Syncfusion.Pdf; -using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Graphics; -using Syncfusion.Pdf.Grid; +using System; +using System.Drawing; +using System.IO; +using Xamarin.Forms; {% endhighlight %} {% endtabs %} -Step 7: Include the following code example in the click event of the button in *MainXamlPage.xaml.cs*, to create a PDF document and save it in a stream. In this code example, the [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html) object represents an entire PDF document that is being created and add a [PdfPage](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfPage.html) to it. The text has been added in PDF by using the [DrawString](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawString_System_String_Syncfusion_Pdf_Graphics_PdfFont_Syncfusion_Pdf_Graphics_PdfBrush_System_Drawing_PointF_) method of [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html) class. - +### Step 7: Create the PDF generation method + +Add the following event handler to `MainXamlPage.xaml.cs`. This creates a PDF document using [PdfDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.PdfDocument.html), adds a page, and draws text using the [DrawString](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html#Syncfusion_Pdf_Graphics_PdfGraphics_DrawString_System_String_Syncfusion_Pdf_Graphics_PdfFont_Syncfusion_Pdf_Graphics_PdfBrush_System_Drawing_PointF_) method of [PdfGraphics](https://help.syncfusion.com/cr/document-processing/Syncfusion.Pdf.Graphics.PdfGraphics.html). The document is saved to a stream and passed to the platform-specific `ISave` service for file saving. + {% tabs %} {% highlight c# tabtitle="C#" %} -private void Button_Clicked(object sender, EventArgs e) +private void OnButtonClicked(object sender, EventArgs e) { - //Create a new PDF document. - PdfDocument document = new PdfDocument(); - //Add a page to the document. - PdfPage page = document.Pages.Add(); - //Create PDF graphics for the page. - PdfGraphics graphics = page.Graphics; - //Set the standard font. - PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); - //Draw the text. - graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); - //Save the document to the stream. - MemoryStream stream = new MemoryStream(); - document.Save(stream); - //Close the document. - document.Close(true); - //Save the stream as a file in the device and invoke it for viewing. - Xamarin.Forms.DependencyService.Get().SaveAndView("Output.pdf", "application/pdf", stream); + try + { + //Create a new PDF document. + using (PdfDocument document = new PdfDocument()) + { + //Add a page to the document. + PdfPage page = document.Pages.Add(); + //Create PDF graphics for the page. + PdfGraphics graphics = page.Graphics; + //Set the standard font. + PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); + //Draw the text. PointF(0, 0) represents the top-left corner in pixels. + graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); + + //Save the document to a memory stream. + MemoryStream stream = new MemoryStream(); + document.Save(stream); + stream.Position = 0; + + //Pass the stream to the platform-specific save service. + DependencyService.Get().SaveAndView("Output.pdf", "application/pdf", stream); + } + } + catch (Exception ex) + { + DisplayAlert("Error", "Error generating PDF: " + ex.Message, "OK"); + } } {% endhighlight %} {% endtabs %} -Step 8: Download the helper files from this [link](https://www.syncfusion.com/downloads/support/directtrac/general/ze/Helper_Class1305995392) and add them into the mentioned project. These helper files allow you to save the stream as a physical file and open the file for viewing. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ProjectFile NameSummary
portable projectISave.cs Represent the base interface for save operation
iOS ProjectSaveIOS.csRepresent the base interface for save operation
PreviewControllerDS.csHelper class for viewing the PDF file in iOS device
Android projectSaveAndroid.csSave implementation for Android device
WinPhone projectSaveWinPhone.csSave implementation for Windows Phone device
UWP projectSaveWindows.csSave implementation for UWP device.
Windows(8.1) project SaveWindows81.csSave implementation for WinRT device.
- -N> Android introduced a new runtime permission model for SDK version 23 and above. Include the following code to enable the Android file provider to save and view the generated PDF document. - -Step 9(i): Create a new XML file with the name of provider_paths.xml under the Android project Resources folder and add the following code in it. -Eg: Resources/xml/provider_paths.xml +## Platform-Specific Implementation + +### Step 8: Define the ISave interface + +Create the `ISave.cs` interface in the portable project. This interface defines the contract for platform-specific file saving implementations: + +{% tabs %} +{% highlight c# tabtitle="C#" %} + +using System.IO; + +public interface ISave +{ + //Method to save document as a file and view the saved document. + void SaveAndView(string filename, string contentType, MemoryStream stream); +} + +{% endhighlight %} +{% endtabs %} + +### Step 9: Download and configure platform-specific implementations + +Download the helper files from this [link](https://www.syncfusion.com/downloads/support/directtrac/general/ze/Helper_Class1305995392). These files provide platform-specific implementations of the `ISave` interface for each platform. Add them to the following project locations: + +| Project | File Name | Location | Summary | +|---------|-----------|----------|---------| +| Portable | ISave.cs | Project root | Interface definition for save operation (shown above) | +| iOS | SaveIOS.cs | iOS project root | iOS-specific save and preview implementation | +| iOS | PreviewControllerDS.cs | iOS project root | Helper class for QuickLook PDF preview | +| Android | SaveAndroid.cs | Android project root | Android-specific save implementation | +| Windows Phone | SaveWinPhone.cs | WinPhone project root | Windows Phone save implementation (legacy) | +| UWP | SaveWindows.cs | UWP project root | UWP-specific save implementation | +| Windows 8.1 | SaveWindows81.cs | Windows project root | Windows 8.1 WinRT save implementation (legacy) | + +### Step 10: Register DependencyService implementations + +For each platform project, register the `ISave` implementation in the platform-specific Main class or AppDelegate: + +**iOS (AppDelegate.cs):** +```csharp +LoadApplication(new App()); +DependencyService.Register(); +``` + +**Android (MainActivity.cs):** +```csharp +LoadApplication(new App()); +DependencyService.Register(); +``` + +**UWP (App.xaml.cs):** +```csharp +DependencyService.Register(); +``` + +### Step 11: Configure Android permissions and file provider + +#### Android Configuration + +Create a new XML file named `provider_paths.xml` in the `Android/Resources/xml` folder (create the xml folder if it doesn't exist): {% tabs %} {% highlight XML %} @@ -158,28 +218,38 @@ Eg: Resources/xml/provider_paths.xml + + + {% endhighlight %} {% endtabs %} -Step 9(ii): Add the following code to the AndroidManifest.xml file located under Properties/AndroidManifest.xml. +Update `Properties/AndroidManifest.xml` to add the FileProvider configuration and permissions: {% tabs %} {% highlight XML %} + + package="com.companyname.gettingstarted"> + android:minSdkVersion="21" + android:targetSdkVersion="33" /> @@ -188,41 +258,66 @@ Step 9(ii): Add the following code to the AndroidManifest.xml file located under android:resource="@xml/provider_paths" /> + + + + + {% endhighlight %} {% endtabs %} -**Include the following changes when deploying the application on Android 11:** +**For Android 11+ deployments:** -* Enable the `android:requestLegacyExternalStorage` attribute in the AndroidManifest.xml file when required. +Add the following attribute to the `` tag: +```xml +android:requestLegacyExternalStorage="true" +``` -{% tabs %} -{% highlight XML %} +> **Note:** The `${applicationId}` placeholder is automatically replaced by the build system; do not edit manually. Android 6.0 (API 23+) requires runtime permissions; FileProvider handles secure file access. - +#### iOS Configuration -{% endhighlight %} -{% endtabs %} +For iOS, add the following key to `Info.plist` to describe file access usage: -* User permission for read or write external storage.Add the following code to the AndroidManifest.xml file located under Properties/AndroidManifest.xml. +```xml +NSPhotoLibraryAddUsageDescription +This app needs access to your photo library to save PDF files. +``` -{% tabs %} -{% highlight XML %} +> **Note:** iOS uses QuickLook framework (included in helper files) for PDF preview. - - - +### Step 12: Build and run the application -{% endhighlight %} -{% endtabs %} +Build and execute the application on your target platform(s): + +1. Click the **Generate Document** button to create the PDF +2. The platform-specific save handler will save the file to the device's default documents folder +3. A preview or native file viewer will open automatically (depending on platform) + +**Expected output:** A PDF file named `Output.pdf` containing "Hello World!!!" text. + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| "NuGet package not found" error | Verify NuGet source is configured; ensure Syncfusion.Xamarin.PDF package version matches your .NET version | +| "ISave interface not found" or "DependencyService failed to resolve" | Ensure ISave.cs is in portable project; verify platform-specific SaveXxx.cs files exist; confirm DependencyService.Register() called in platform projects | +| "Permission denied" on Android | Verify Android/Resources/xml/provider_paths.xml exists; check AndroidManifest.xml has required permissions (READ/WRITE_EXTERNAL_STORAGE) | +| "File not saving" on device | Check device storage permissions; verify app has write access to Documents folder on iOS; ensure Android SDK version ≥21 | +| "PDF preview not showing" on iOS | Verify PreviewControllerDS.cs helper file is in iOS project; check QuickLook framework is available | +| "Handler method not found" | Ensure XAML `OnButtonClicked` matches C# method name exactly (case-sensitive) | +| "Licensing" errors at runtime | Install Syncfusion.Licensing NuGet package; register valid license key in App constructor or App.xaml.cs | -Step 10: Compile and execute the application. This will create a simple PDF document. +## Next Steps -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Xamarin/CreatePDFDocument). +- **Download [Complete Working Sample](https://github.com/SyncfusionExamples/PDF-Examples/tree/master/Getting%20Started/Xamarin/CreatePDFDocument)** — Reference implementation with all platforms +- **Try [Online Demo](https://document.syncfusion.com/demos/pdf/default#/tailwind)** — Interactive PDF generation examples +- **Migrate to [.NET MAUI](https://help.syncfusion.com/document-processing/pdf/pdf-library/net/create-pdf-document-in-blazor)** — Use modern cross-platform framework (Xamarin is deprecated) +- **Explore [Syncfusion PDF Features](https://www.syncfusion.com/document-sdk/net-pdf-library)** — Complete API reference and advanced capabilities -By executing the program, you will get the PDF document as follows. -![Xamarin output PDF document](GettingStarted_images/pdf-generation-output.png) +## Sample Output -Click [here](https://www.syncfusion.com/document-sdk/net-pdf-library) to explore the rich set of Syncfusion® PDF library features. +By executing the application and clicking **Generate Document**, you will get the following output: -An online sample link to [create PDF document](https://document.syncfusion.com/demos/pdf/default#/tailwind). \ No newline at end of file +![Xamarin output PDF document](GettingStarted_images/pdf-generation-output.png) \ No newline at end of file diff --git a/Document-Processing/PDF/PDF-Library/flutter/getting-started.md b/Document-Processing/PDF/PDF-Library/flutter/getting-started.md index 4e97dfebc8..0be0f00d90 100644 --- a/Document-Processing/PDF/PDF-Library/flutter/getting-started.md +++ b/Document-Processing/PDF/PDF-Library/flutter/getting-started.md @@ -1,20 +1,30 @@ --- layout: post -title: Getting started with Flutter PDF library | Syncfusion -description: Learn here about getting started with Syncfusion Flutter PDF non-UI library, its elements, and more. +title: Getting Started with Syncfusion Flutter PDF Library | Syncfusion +description: Learn how to get started with Syncfusion Flutter PDF library, create PDF documents, and explore key features. platform: document-processing control: PDF documentation: ug --- -# Getting started with Flutter PDF +# Getting Started with Syncfusion Flutter PDF -This section explains the steps required to create a [Flutter PDF library](https://www.syncfusion.com/document-processing/pdf-framework/flutter/pdf-library) document by a single button click. This section covers only the minimal features needed to learn to get started with the PDF. +This section explains the steps required to create a [Syncfusion Flutter PDF](https://www.syncfusion.com/document-processing/pdf-framework/flutter/pdf-library) document with a single button click. This section covers minimal features needed to get started with PDF generation. Check the following video to quickly get started with creating a Flutter PDF document. {% youtube "https://youtu.be/tMM9ty4Wfq0?si=b3EBPP0mjVpLKdBJ" %} -## Steps to create PDF document in Flutter application +## Prerequisites + +| Requirement | Version | +|---|---| +| **Flutter SDK** | 2.10 or later | +| **Dart SDK** | 2.16 or later | +| **IDE** | Android Studio, Xcode, or Visual Studio Code | +| **Syncfusion Flutter PDF package** | Latest stable version | +| **Supported Platforms** | Android, iOS, Web, Windows, macOS, Linux | + +## Steps to Create a PDF Document in Flutter Create a simple project using the instructions given in the [`Getting Started with your first Flutter app`](https://docs.flutter.dev/get-started/test-drive#choose-your-ide) documentation. @@ -77,67 +87,82 @@ Widget build(BuildContext context) { {% endhighlight %} {% endtabs %} -Include the following code snippet in the button click event to create a PDF file. +Add the following code snippet in the button click event to create a simple PDF file: {% tabs %} {% highlight dart tabtitle="dart" %} Future _createPDF() async { - //Create a new PDF document - PdfDocument document = PdfDocument(); - - //Add a new page and draw text - document.pages.add().graphics.drawString( - 'Hello World!', - PdfStandardFont(PdfFontFamily.helvetica, 20), - brush: PdfSolidBrush(PdfColor(0, 0, 0)), - bounds: Rect.fromLTWH(0, 0, 500, 50), - ); + try { + //Create a new PDF document + PdfDocument document = PdfDocument(); + + //Add a new page and draw text + document.pages.add().graphics.drawString( + 'Hello World!', + PdfStandardFont(PdfFontFamily.helvetica, 20), + brush: PdfSolidBrush(PdfColor(0, 0, 0)), + bounds: Rect.fromLTWH(0, 0, 500, 50), + ); - //Save the document - List bytes = await document.save(); + //Save the document + List bytes = await document.save(); - //Dispose the document - document.dispose(); + //Dispose the document + document.dispose(); + + // Now use platform-specific code to save/open the file + // See sections below for platform-specific implementations + } catch (e) { + print('Error creating PDF: $e'); + } } {% endhighlight %} {% endtabs %} -## Save and open a PDF document in desktop +N> Always wrap document operations in try-catch blocks and ensure `document.dispose()` is called to free resources. + +## Save and Open a PDF Document on Desktop -You can save and open a PDF document in desktop by using the following steps: +You can save and open a PDF document on desktop (Windows, macOS, Linux) using the following steps: -**Set up** +**Step 1: Configure Desktop Support** -Configure and enable the desktop support to run the app. +Enable desktop support for your target platform: {% tabs %} -{% highlight dart tabtitle="dart" %} +{% highlight bash tabtitle="bash" %} + +# For Windows +flutter config --enable-windows-desktop + +# For macOS +flutter config --enable-macos-desktop -flutter config --enable--desktop +# For Linux +flutter config --enable-linux-desktop {% endhighlight %} {% endtabs %} -N> You only need to execute `flutter config --enable--desktop` once. You can always check the status of your configuration using the no-argument flutter config command. +N> You only need to run the `flutter config` command once. For details, see [`Adding desktop support to Flutter apps`](https://docs.flutter.dev/desktop). -Here you can get more details about [`How to add desktop support in the app`](https://docs.flutter.dev/desktop) +**Step 2: Add Dependencies** -**Add dependency** - -Add the following packages to your pub spec file. +Add the following packages to your **pubspec.yaml** file: {% tabs %} -{% highlight dart tabtitle="dart" %} +{% highlight yaml tabtitle="yaml" %} -path_provider: ^2.0.7 -open_file: ^3.2.1 +dependencies: + path_provider: ^2.0.7 + open_file: ^3.2.1 {% endhighlight %} {% endtabs %} -**Import package** +**Step 3: Import Required Packages** {% tabs %} {% highlight dart tabtitle="dart" %} @@ -149,13 +174,15 @@ import 'package:path_provider/path_provider.dart'; {% endhighlight %} {% endtabs %} -Include the following code snippet in _createPDF method to open the PDF document in mobile after saving it. +**Step 4: Save and Open PDF on Desktop** + +Add the following code snippet in your `_createPDF` method to save and open the PDF document: {% tabs %} {% highlight dart tabtitle="dart" %} -//Get external storage directory -final directory = await getExternalStorageDirectory(); +//Get the documents directory (platform-specific) +final directory = await getApplicationDocumentsDirectory(); //Get directory path final path = directory.path; @@ -166,30 +193,33 @@ File file = File('$path/Output.pdf'); //Write PDF data await file.writeAsBytes(bytes, flush: true); -//Open the PDF document in mobile +//Open the PDF document with the default viewer OpenFile.open('$path/Output.pdf'); {% endhighlight %} {% endtabs %} -## Save and open a PDF document in mobile +N> `getApplicationDocumentsDirectory()` returns the standard documents folder on all desktop platforms. Alternatively, use `getDownloadsDirectory()` for the Downloads folder. -You can save and open a PDF document in mobile by using the following steps: +## Save and Open a PDF Document on Mobile -**Add dependency** +You can save and open a PDF document on mobile platforms (Android and iOS) using the following steps: + +**Step 1: Add Dependencies** -Add the following packages to your pub spec file. +Add the following packages to your **pubspec.yaml** file: {% tabs %} -{% highlight dart tabtitle="dart" %} +{% highlight yaml tabtitle="yaml" %} -path_provider: ^2.0.7 -open_file: ^3.2.1 +dependencies: + path_provider: ^2.0.7 + open_file: ^3.2.1 {% endhighlight %} {% endtabs %} -**Import package** +**Step 2: Import Required Packages** {% tabs %} {% highlight dart tabtitle="dart" %} @@ -201,12 +231,14 @@ import 'package:path_provider/path_provider.dart'; {% endhighlight %} {% endtabs %} -Include the following code snippet in _createPDF method to open the PDF document in mobile after saving it. +**Step 3: Save and Open PDF on Mobile** + +Add the following code snippet in your `_createPDF` method to save and open the PDF document: {% tabs %} {% highlight dart tabtitle="dart" %} -//Get external storage directory +//Get application support directory (works on Android and iOS) final directory = await getApplicationSupportDirectory(); //Get directory path @@ -218,17 +250,19 @@ File file = File('$path/Output.pdf'); //Write PDF data await file.writeAsBytes(bytes, flush: true); -//Open the PDF document in mobile -OpenFile.open('$path/Output.pdf'); +//Open the PDF document with the default viewer +await OpenFile.open('$path/Output.pdf'); {% endhighlight %} {% endtabs %} -## Save and download a PDF document in web +N> For Android 10 and above, ensure your app has the required permissions in `AndroidManifest.xml`. For iOS, add file sharing capabilities in `Info.plist`. -You can save and download a PDF document in web by using the following steps. +## Save and Download a PDF Document on Web -**Import package** +You can save and download a PDF document in web applications using JavaScript interop. This approach works with Dart code targeting the web platform. + +**Step 1: Import Required Packages** {% tabs %} {% highlight dart tabtitle="dart" %} @@ -240,83 +274,125 @@ import 'dart:js' as js; {% endhighlight %} {% endtabs %} -Include the following code snippet in _createPDF method to open the document in web after saving it. +N> This uses the legacy `dart:js` API. For Dart 3.0+, consider using `dart:js_interop` package for better type safety and null safety support. + +**Step 2: Add Download Logic to _createPDF Method** + +Add the following code snippet in your `_createPDF` method to trigger the browser download: {% tabs %} {% highlight dart tabtitle="dart" %} -js.context['pdfData'] = base64.encode(bytes); -js.context['filename'] = 'Output.pdf'; -Timer.run(() { - js.context.callMethod('download'); -}); +try { + js.context['pdfData'] = base64.encode(bytes); + js.context['filename'] = 'Output.pdf'; + Timer.run(() { + js.context.callMethod('download'); + }); +} catch (e) { + print('Error downloading PDF: $e'); +} {% endhighlight %} {% endtabs %} -Add the following code in the header section of index.html file under the web folder. +**Step 3: Add JavaScript Download Function** + +Add the following code in the `` section of **web/index.html**: {% tabs %} -{% highlight dart tabtitle="dart" %} +{% highlight html tabtitle="html" %} {% endhighlight %} {% endtabs %} -## Save and download a PDF document in WASM +## Save and Download a PDF Document with WASM -**Step 1:** Add the [web](https://pub.dev/packages/web) package as a dependency in your **pubspec.yaml** file. +For Dart 3.0+ web apps, use the modern `dart:js_interop` API with WASM (WebAssembly) support instead of legacy JavaScript interop. -**Step 2:** Create a new Dart file called **save_file_wasm.dart**. +**Step 1: Add Dependencies** -**Step 3:** Add the following code: +Add the [web](https://pub.dev/packages/web) package to your **pubspec.yaml**: -**Import package** +{% tabs %} +{% highlight yaml tabtitle="yaml" %} + +dependencies: + web: ^0.5.0 + +{% endhighlight %} +{% endtabs %} + +**Step 2: Create Save Function** + +Create a new Dart file called **save_file_wasm.dart** with the following code: {% tabs %} {% highlight dart tabtitle="dart" %} import 'dart:convert'; +import 'dart:typed_data'; import 'package:web/web.dart' as web; +/// Function to save and download a file in a WASM web environment +Future saveAndLaunchFile(Uint8List bytes, String fileName) async { + try { + final blob = web.Blob([bytes], 'application/pdf'); + final url = web.URL.createObjectURL(blob); + + final anchor = web.document.createElement('a') as web.HTMLAnchorElement + ..href = url + ..download = fileName + ..style.display = 'none'; + + // Add to DOM, click, and clean up + web.document.body!.appendChild(anchor); + anchor.click(); + web.document.body!.removeChild(anchor); + + // Release object URL + web.URL.revokeObjectURL(url); + } catch (e) { + print('Error saving PDF: $e'); + } +} + {% endhighlight %} {% endtabs %} -To enable file saving and launching for download in a web environment, include the following code snippet within the **saveAndLaunchFile** method. +**Step 3: Call from PDF Creation Method** + +Update your `_createPDF` method to call this function: {% tabs %} {% highlight dart tabtitle="dart" %} -// Function to save and launch a file for download in a web environment -Future saveAndLaunchFile(List bytes, String fileName) async { - final web.HTMLAnchorElement anchor = - web.document.createElement('a') as web.HTMLAnchorElement - ..href = "data:application/octet-stream;base64,${base64Encode(bytes)}" - ..style.display = 'none' - ..download = fileName; - - // Insert the new element into the DOM - web.document.body!.appendChild(anchor); - - // Initiate the download - anchor.click(); - // Clean up the DOM by removing the anchor element - web.document.body!.removeChild(anchor); -} +// In your _createPDF method, after creating the PDF: +List bytes = await document.save(); +await saveAndLaunchFile(Uint8List.fromList(bytes), 'Output.pdf'); {% endhighlight %} {% endtabs %} +N> WASM approach is more efficient than JavaScript interop and provides better performance for large PDF files. It's the recommended approach for modern Flutter web apps. + By executing the above code sample, you will get the PDF document as follows. ![Getting started PDF](images/getting-started/default.jpg) @@ -429,7 +505,7 @@ PdfGraphics graphics = page.graphics; * In PDF, all the elements are placed in absolute positions and has the possibility for content overlapping if misplaced. * Syncfusion® PDF provides the rendered bounds for each and every element added through [`PdfLayoutResult`](https://pub.dev/documentation/syncfusion_flutter_pdf/latest/pdf/PdfLayoutResult-class.html) objects. This can be used to add successive elements and prevent content overlap. -The following code example explains how to add an image from base64 string to a PDF document, by providing the rectangle coordinates. +The following code example demonstrates how to add an image from a base64 string to a PDF document by specifying the rectangle coordinates: {% tabs %} {% highlight dart tabtitle="dart" %} @@ -729,4 +805,17 @@ The following screenshot shows the invoice PDF document created by the Syncfusio ![Invoice PDF](images/getting-started/invoice.jpg) -N> You can also explore our [Flutter PDF library](https://github.com/syncfusion/flutter-examples/tree/master/lib/samples/pdf) demo that shows how to create and modify PDF files from C# with just five lines of code. \ No newline at end of file +N> You can also explore our [Syncfusion Flutter PDF library](https://github.com/syncfusion/flutter-examples/tree/master/lib/samples/pdf) demo that shows how to create and modify PDF files from Dart with just a few lines of code. + +## Next Steps + +Explore advanced features and common use cases with the Syncfusion Flutter PDF library: + +- [Merge PDF Documents](./merge-pdf-documents.md) - Combine multiple PDF files into a single document +- [Split PDF Documents](./split-pdf-documents.md) - Extract pages or divide PDFs into separate files +- [Add Watermarks](./add-watermark.md) - Apply text and image watermarks to PDFs +- [Work with Forms](./fill-form-fields.md) - Create and fill interactive PDF forms +- [Secure Documents](./encrypt-pdf.md) - Add passwords and encryption for PDF security +- [Other Platforms](../../getting-started.md) - PDF generation guides for other platforms (ASP.NET Core, WPF, Android, iOS, and more) + +For more examples and complete API documentation, visit the [Syncfusion Flutter PDF documentation](https://help.syncfusion.com/flutter/pdf/overview). \ No newline at end of file