Come creare PDF in C#

Questa guida pratica spiega come creare PDF in C#. Puoi generare PDF da C# seguendo i semplici passaggi indicati di seguito in alcune chiamate API per qualsiasi applicazione basata su .NET.

Passaggi per creare PDF in C#

  1. Installa Aspose.PDF for .NET utilizzando il gestore di pacchetti NuGet
  2. Includere il riferimento Aspose.PDF nell’applicazione
  3. Crea un’istanza della classe Document per creare un PDF vuoto
  4. Crea un’istanza della classe TextFragment per aggiungere testo e le sue proprietà
  5. Infine, crea PDF usando C# salvando su disco

L’esempio seguente spiega come generare PDF in C#. Vedrai come creare un PDF vuoto usando Document Class e aggiungendo una pagina al suo interno. Quindi utilizzando TextBuilder Class il testo viene aggiunto e vengono impostate le rispettive proprietà. Infine, il testo verrà allegato al PDF.

Codice per creare PDF da C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Aspose.Pdf;
using Aspose.Pdf.Annotations;
using Aspose.Pdf.Devices;
using Aspose.Pdf.Facades;
using Aspose.Pdf.Forms;
using Aspose.Pdf.Text;
namespace TestPDF
{
class Program
{
static void Main(string[] args)
{
// Applying product license to create PDF in C#
License lic = new License();
lic.SetLicense("Total.Product.Family.lic");
// Initialize document object generate PDF from C#
Document document = new Document();
// Insert page in PDF
Page pdfPage = document.Pages.Add();
// Create instance of Text fragment
TextFragment textFragment = new TextFragment("Knowledgebase Text");
// Set textual properties
textFragment.Position = new Position(100, 600);
textFragment.TextState.FontSize = 12;
textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman");
textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray);
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Red);
// Initialize TextBuilder object
TextBuilder textBuilder = new TextBuilder(pdfPage);
// Append added fragment to the PDF page
textBuilder.AppendText(textFragment);
// Create PDF using C#
document.Save("Generated_out.pdf");
}
}
}

Nel codice di esempio sopra, abbiamo osservato come creare file PDF in C# senza dipendere da Adobe PDF o da qualsiasi altra API. Utilizzando poche semplici chiamate API, abbiamo creato un PDF da zero aggiungendo del testo e impostandone le rispettive proprietà.

Nell’argomento precedente, hai imparato a leggi PDF in C#. Considerando che la spiegazione sopra e il codice di esempio in C# creano file PDF a livello di codice.

 Italiano