Pdfium.Net SDK es la biblioteca .Net, líder para crear, editar, transformar y visualizar documentos en formato portátil (PDF). Proporcionamos una API C# de alto nivel para crear dinámicamente archivos PDF en un servidor web o cualquier otro sistema back-end, así como para implementar la función "Guardar como PDF" en aplicaciones de escritorio o web existentes.
/// <summary>
/// Create PDF Document on The Fly in C# using Pdfium.Net SDK Library
/// </summary>
public void CreatePdf()
{
// The PDF coordinate system origin is at the bottom left corner of the page.
// The X-axis is pointing to the right. The Y-axis is pointing in upward direction.
// The sizes and coordinates in this method are given in the inches.
// Step 1: Initialize PDF library and create empty document
// Return value: PdfDocument main class
PdfCommon.Initialize();
var doc = PdfDocument.CreateNew(); // Create a PDF document
// Step 2: Add new page
// Arguments: page width: 8.27", page height: 11.69", Unit of measure: inches
// The PDF unit of measure is point. There are 72 points in one inch.
var page = doc.Pages.InsertPageAt(doc.Pages.Count, 8.27f * 72, 11.69f * 72);
// Step 3: Add graphics and text contents to the page
// Insert image from file using standart System.Drawing.Bitmap class
using (PdfBitmap logo = PdfBitmap.FromFile(@"e:\63\logo_square.png"))
{
PdfImageObject imageObject = PdfImageObject.Create(doc, logo, 0, 0);
//image resolution is 300 DPI and location is 1.69 x 10.0 inches.
imageObject.Matrix = new FS_MATRIX(logo.Width * 72 / 300, 0, 0, logo.Height * 72 / 300, 1.69 * 72, 10.0 * 72);
page.PageObjects.Add(imageObject);
}
// Create fonts used for text objects
PdfFont calibryBold = PdfFont.CreateFont(doc, "CalibriBold");
// Insert text objects at 7.69"; 11.02" and font size is 25
PdfTextObject textObject = PdfTextObject.Create("Sample text", 1.69f * 72, 11.02f * 72, calibryBold, 25);
textObject.FillColor = FS_COLOR.Black;
page.PageObjects.Add(textObject);
// Step 5: Generate page content and save pdf file
// argument: PDF file name
page.GenerateContent();
doc.Save(@"e:\63\sample_document.pdf", SaveFlags.NoIncremental);
}
La biblioteca C# Pdfium.Net SDK permite a los desarrolladores crear documentos PDF fácilmente. Este ejemplo ilustra cómo crear un documento de este tipo utilizando objetos de página.
Puede crear objetos de página de diferentes tipos (texto, imágenes, contornos, formas, etc.) y colocarlos en cualquier lugar de la página.
/// <summary>
/// Generate PDF document From Multiple Images in C# using PDF Library
/// </summary>
public void GeneratePdf()
{
//Initialize C# PDF Library
PdfCommon.Initialize();
//Create a PDF document
using (var doc = PdfDocument.CreateNew())
{
//Read images
var files = System.IO.Directory.GetFiles(@"c:\Images\", "*.*",
System.IO.SearchOption.AllDirectories);
foreach (var file in files)
{
//Create empty PdfBitmap
using (PdfBitmap pdfBitmap = PdfBitmap.FromFile(file))
{
//Create Image object
var imageObject = PdfImageObject.Create(doc, pdfBitmap, 0, 0);
//Calculate size of image in PDF points
var size = CalculateSize(pdfBitmap.Width, pdfBitmap.Height);
//Add empty page to PDF document
var page = doc.Pages.InsertPageAt(doc.Pages.Count, size);
//Insert image to newly created page
page.PageObjects.Add(imageObject);
//set image matrix
imageObject.Matrix = new FS_MATRIX(size.Width, 0, 0, size.Height, 0, 0);
//Generate PDF page content to content stream
page.GenerateContent();
}
}
// Save PDF document as "saved.pdf" in no incremental mode
doc.Save(@"c:\test.pdf", SaveFlags.NoIncremental);
}
}
/// <summary>
/// The function takes width and height of the bitmap in pixels as well as
/// horizontal and vertical DPI and calculates the size of the PDF page.
/// To understand the conversion you should know the following:
/// One inch contains exactly 72 PDF points;
/// DPI of the scanned image may vфry and depends on scanning resolution
/// <summary>
private FS_SIZEF CalculateSize(int width, int height, float dpiX=300, float dpiY=300)
{
return new FS_SIZEF()
{
Width = width * 72 / dpiX,
Height = height * 72 / dpiY
};
}
Este ejemplo muestra cómo crear un documento PDF a partir de un conjunto de imágenes escaneadas utilizando código C# simple y la biblioteca PDF.
/// <summary>
/// Printing PDF Files in C# using PDF Library
/// </summary>
public void PrintPdf()
{
var doc = PdfDocument.Load("c:\test.pdf"); // Read PDF file
var printDoc = new PdfPrintDocument(doc);
printDoc.Print();
}
El código anterior imprime el documento PDF en la impresora predeterminada. También se muestra un cuadro de diálogo de impresión estándar con el progreso de la impresión. Si desea ocultar la ventana de progreso, cambie el código como se muestra a continuación.
public void PrintPdf()
{
var doc = PdfDocument.Load("c:\test.pdf");
var printDoc = new PdfPrintDocument(doc);
PrintController printController = new StandardPrintController();
printDoc.PrintController = printController;
printDoc.Print(); // C# Print PDF document
}
PdfPrintDocument se deriva de la clase estándar PrintDocument, por lo que puede utilizar el cuadro de diálogo de impresión de .Net Framework (PrinterDialog), que personaliza PrintDocument según la entrada del usuario.
public void OnPrintClick()
{
if (PdfViewer.Document.FormFill != null)
PdfViewer.Document.FormFill.ForceToKillFocus();
//create an instance of PrintDocument class
var printDoc = new PdfPrintDocument(PdfViewer.Document); // create an instance of Print document class that is used for printing PDF document.
//Create a standard print dialog box
var dlg = new PrintDialog();
dlg.AllowCurrentPage = true;
dlg.AllowSomePages = true;
dlg.UseEXDialog = true;
//sets the PrintDocument used to obtain PrinterSettings.
dlg.Document = printDoc;
//show PrinterDialog and print pdf document
if (dlg.ShowDialog() == DialogResult.OK)
printDoc.Print(); // C# Print PDF
}
/// <summary>
/// Read PDF File and Extract Text From it in C#
/// </summary>public void ExtractText()
{
//Initialize the SDK library
//You have to call this function before you can call any PDF processing functions.
PdfCommon.Initialize();
//Open and load a PDF document from a file.
using (var doc = PdfDocument.Load(@"c:\test001.pdf")) // C# Read PDF File
{
foreach (var page in doc.Pages)
{
//Gets number of characters in a page or -1 for error.
//Generated characters, like additional space characters, new line characters, are also counted.
int totalCharCount = page.Text.CountChars;
//Extract text from page to the string
string text = page.Text.GetText(0, totalCharCount);
page.Dispose();
}
}
}
El SDK de Pdfium.Net permite a los desarrolladores extraer fácilmente el texto completo de prácticamente cualquier archivo PDF.
/// <summary>
/// Search for a Text in a PDF File in C# With Pdfium.Net SDK Library
/// </summary>
public void Search()
{
//Open PDF document
using (var doc = PdfDocument.Load(@"d:\0\test_big.pdf")) // Read PDF document and enumerate pages
{
//Enumerate pages
foreach(var page in doc.Pages)
{
var found = page.Text.Find("text for search", FindFlags.MatchWholeWord, 0);
if (found == null)
return; //nothing found
do
{
var textInfo = found.FoundText;
foreach(var rect in textInfo.Rects)
{
float x = rect.left;
float y = rect.top;
//...
}
} while (found.FindNext());
page.Dispose();
}
}
}
Este ejemplo muestra cómo buscar texto en un documento utilizando código C# simple y una biblioteca PDF.
/// <summary>
/// Search for a Text Asynchronously in C# using PDF Library
/// </summary>
public void SearchAsync()
{
//Open PDF document
var doc = PdfDocument.Load(@"c:\test_big.pdf"); // C# Read PDF File
PdfSearch search = new PdfSearch(doc);
search.FoundTextAdded += (s, e) =>
{
var textInfo = doc.Pages[e.FoundText.PageIndex].Text.GetTextInfo(e.FoundText.CharIndex, e.FoundText.CharsCount);
foreach (var rect in textInfo.Rects)
{
float x = rect.left;
float y = rect.top;
Console.WriteLine(string.Format("Found text: {0}, Page = {1}, x= {2}, y={3}", textInfo.Text, e.FoundText.PageIndex, x, y));
//...
}
};
search.SearchCompleted += (s, e) =>
{
doc.Dispose();
};
search.SearchProgressChanged += (s, e) =>
{
Console.WriteLine(string.Format("Progress: {0}%", e.ProgressPercentage));
};
search.Start("document", FindFlags.MatchWholeWord);
Console.ReadLine();
}
Este ejemplo muestra cómo puede utilizar la biblioteca PDF de C# para buscar texto de forma asincrónica.
/// <summary>
/// Extract Text Coordinates from Pdf in C# using PDF Library
/// </summary>
public void ExtractTextInfo()
{
//Initialize the SDK library
//You have to call this function before you can call any PDF processing functions.
PdfCommon.Initialize();
//Open and load a PDF document from a file.
using (var doc = PdfDocument.Load(@"c:\test001.pdf")) // C# Read PDF File
{
//Get second page from document
using (var page = doc.Pages[1])
{
//Extract text information structure from the page
// 10 - Index for the start characters
// 25 - Number of characters to be extracted
var textInfo = page.Text.GetTextInfo(10, 25);
//Gets text from textInfo strtucture
string text = textInfo.Text;
//Gets a collection of rectangular areas bounding specified text.
var rects = textInfo.Rects;
}
}
}
El SDK de Pdfium.Net también permite a los desarrolladores extraer fácilmente coordenadas de texto de cualquier archivo PDF.
/// <summary>
/// Extracting Images from Pdf File With .Net C# and PDF Library
/// </summary>
private int _writedImageIndex = 0;
public void ExtractAllImages()
{
//Initialize the SDK library
//You have to call this function before you can call any PDF processing functions.
PdfCommon.Initialize();
//Open and load a PDF document from a file.
using (var doc = PdfDocument.Load(@"c:\test001.pdf")) // C# Read PDF File
{
//Enumerate all pages sequentially in a given document
foreach (var page in doc.Pages)
{
//Extract and save images
ExtractImagesFromPage(page);
//dipose page object to unload it from memory
page.Dispose();
}
}
}
private void ExtractImagesFromPage(PdfPage page)
{
//Enumerate all objects on a page
foreach (var obj in page.PageObjects)
{
var imageObject = obj as PdfImageObject;
if (imageObject == null)
continue; //if not an image object then nothing do
//Save image to disk
var path = string.Format(@"c:\\Images\\image_{0}.png", ++_writedImageIndex);
imageObject.Bitmap.Image.Save(path, ImageFormat.Png);
}
}
El ejemplo muestra cómo extraer imágenes de diferentes formatos de un archivo PDF y guardarlas en el disco.
/// <summary>
/// Split PDF in C# using PDF Library
/// </summary>
public void SplitDocument()
{
//Initialize the SDK library
//You have to call this function before you can call any PDF processing functions.
PdfCommon.Initialize();
//Open and load a PDF document from a file.
using (var sourceDoc = PdfDocument.Load(@"c:\test001.pdf")) // C# Read PDF File
{
//Create one PDF document for pages 1-5.
using (var doc = PdfDocument.CreateNew())
{
//Import pages from source document
doc.Pages.ImportPages(sourceDoc, "1-5", 0);
//And save it to doc1.pdf
doc.Save(@"c:\doc1.pdf", SaveFlags.Incremental);
}
//Create another PDF document for pages 5-10.
using (var doc = PdfDocument.CreateNew())
{
//Also import pages
doc.Pages.ImportPages(sourceDoc, "5-10", 0);
//And save them too
doc.Save(@"c:\doc2.pdf", SaveFlags.Incremental);
}
}
}
El siguiente ejemplo de código muestra cómo utilizar la biblioteca PDF para dividir un documento en páginas individuales.
/// <summary>
/// Merge PDFs in C# using PDF Library
/// </summary>
public void MergePdf()
{
//Initialize the SDK library
//You have to call this function before you can call any PDF processing functions.
PdfCommon.Initialize();
//Open and load a PDF document in which will be merged other files
using (var mainDoc = PdfDocument.Load(@"c:\test001.pdf")) // C# Read source PDF File #1
{
//Open one PDF document.
using (var doc = PdfDocument.Load(@"c:\doc1.pdf")) //Read PDF File #2
{
//Import all pages from document
mainDoc.Pages.ImportPages(
doc,
string.Format("1-{0}", doc.Pages.Count),
mainDoc.Pages.Count
);
}
//Open another PDF document.
using (var doc = PdfDocument.Load(@"c:\doc2.pdf"))
{
//Import all pages from document
mainDoc.Pages.ImportPages(
doc,
string.Format("1-{0}", doc.Pages.Count),
mainDoc.Pages.Count
);
}
mainDoc.Save(@"c:\ResultDocument.pdf", SaveFlags.NoIncremental);
}
}
Con la biblioteca PDF de C#, puede seleccionar páginas específicas de archivos de origen y fusionarlas en un solo documento PDF.
Este ejemplo muestra cómo se puede hacer esto utilizando la operación ImportPages.
/// <summary>
/// Render whole PDF document using C# PDF Library
/// </summary>
using (var doc = PdfDocument.Load(@"d:\0\test_big.pdf")) // C# Read PDF Document
{
foreach (var page in doc.Pages)
{
int width = (int)(page.Width / 72.0 * 96);
int height = (int)(page.Height / 72.0 * 96);
using (var bitmap = new PdfBitmap(width, height, true))
{
bitmap.FillRect(0, 0, width, height, Color.White);
page.Render(bitmap, 0, 0, width, height, PageRotate.Normal, RenderFlags.FPDF_LCD_TEXT);
bitmap.Image.Save("...", ImageFormat.Png);
}
}
}
En este ejemplo, creamos un mapa de bits de cada página, por lo que calculamos el ancho y la altura necesarios del mapa de bits en píxeles convertidos a partir de las dimensiones de la página.
El tamaño de la página PDF se especifica en puntos (1 punto equivale a 1/72 de pulgada). Entonces, el DPI de la imagen (96 en este ejemplo) se multiplica por el tamaño de píxel correspondiente y se divide por 72.
Luego, rellenamos todo el mapa de bits con blanco y renderizamos la página en PDF. ¡Eso es todo!
/// <summary>
/// Filling Editable PDF Fields and Extracting Data From Them using .Net PDF Library
/// </summary>
private void btnTest_Click(object sender, RoutedEventArgs e)
{
var forms = new PdfForms();
var doc = PdfDocument.Load(@"c:\test.pdf", forms); // C# Read PDF Document
//doc.FormFill is equal to forms and can be used to get access to acro forms as well;
int i = 0;
foreach(var field in forms.InterForm.Fields)
{
if(field.FieldType == Patagames.Pdf.Enums.FormFieldTypes.FPDF_FORMFIELD_TEXTFIELD)
{
field.Value = "This is a field #" + (++i);
}
}
}
Este ejemplo muestra cómo completar, mediante programación, formularios editables en un documento PDF utilizando la biblioteca .Net PDF.
Cuando compra una licencia de producto, obtiene más que solo una gran biblioteca. Para aprovechar al máximo su experiencia, también obtendrá 12 meses de soporte técnico gratuito directamente de nuestro equipo de desarrollo y actualizaciones gratuitas durante todo un año.
Probé su última versión y funciona muy bien: ¡resuelve ambos problemas! Gracias por satisfacer mi solicitud: se lo agradezco mucho. Todavía utilizamos [otro producto] para algunos proyectos heredados, pero lo hemos eliminado gradualmente para todos los proyectos nuevos. Si bien la biblioteca [other product] en sí es buena, encontramos que su soporte es deficiente; sin lugar a dudas, el soporte de Pdfium.NET SDK fue mucho mejor, tanto en velocidad como en calidad. Gracias de nuevo por el excelente servicio y gran por su producto. -TerryThe link is hidden due to ethical concerns.
El objetivo principal del desarrollo de Pdfium.Net SDK es hacer que las cosas sean simples e intuitivas para los desarrolladores. La biblioteca de clases abstrae todos los detalles del uso de la biblioteca principal de pdfium y proporciona una interfaz basada en objetos mundiales y otras clases intuitivas.
¡Además, Pdfium.Net SDK está bien documentado! Proporcionamos documentación extensa que tiene como objetivo brindar a los usuarios nuevos y experimentados una descripción general de lo que es posible con el SDK de Pdfium.Net.
Uno de nuestros objetivos es proporcionar a los desarrolladores una herramienta de alta calidad para generar dinámicamente archivos PDF en cualquier sistema backend, como Microsoft Azure.
He verificado que su SDK funciona cuando se implementa en Azure (algunos productos que probé no funcionaron; puede promover esto). He realizado la compra.
¡Gracias de nuevo! -Cyberghttps://forum.patagames.com/posts/m1105-Workability-in-various-environments#post1105
¡Agregue capacidad de visualización de PDF a su aplicación .Net! Con múltiples modos de visualización, personalización detallada y compatibilidad total con formularios, el visor de PDF se adapta perfectamente a su aplicación y a su diseño.
El paquete NuGet está disponible en el repositorio oficial en nuget.org.