Pdfium.Net SDK 是领先的 .Net 库,用于生成、操作和查看可移植文档格式的文件。 我们提供高级 c# / VB.Net API,用于在 WEB 服务器或任何其他服务器系统上创建动态 pdf,并在现有桌面或 WEB 应用程序中实现“另存为 PDF”功能。
/// <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);
}
Pdfium.Net SDK库允许开发者在C#中轻松创建PDF文档。这个例子表明,可以使用页面对象动态地创建一个PDF文档。
你可以创建多个页面对象,并把它们放在页面的任何地方。有几种类型的页面对象:路径、表单、图像和文本对象。
/// <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
};
}
这个例子展示了如何使用简单的C#代码和PDF库从一堆扫描的图像中生成一个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();
}
上面的代码将 PDF 文档打印到默认打印机。 还显示了带有打印进度的标准打印对话框。 如果你想抑制进度窗口,请修改如下所示的代码。
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 派生自标准 PrintDocument 类,因此您可以使用 .Net Framework 的打印对话框 (PrinterDialog) 根据用户输入配置 PrintDocument。
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();
}
}
}
Pdfium.Net SDK 允许开发人员轻松地从几乎任何 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();
}
}
}
此示例说明如何使用简单的 C# 代码和 PDF 库在 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();
}
此示例说明如何使用 C# PDF 库异步搜索文本。
/// <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;
}
}
}
Pdfium.Net SDK 还允许开发人员轻松地从任何 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);
}
}
该示例演示了从 pdf 文件中提取不同格式的图像,并将它们保存到磁盘。
/// <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);
}
}
}
下面的代码示例演示了如何使用 C# PDF 库来拆分 PDF 文档。
/// <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);
}
}
使用 C# PDF 库,您不仅可以将多个 PDF 文件合并为一个文件,还可以从源文件中选择特定页面并将它们组合成一个 PDF 文档。
上面的代码展示了如何使用 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);
}
}
}
在此示例中,我们为每个页面创建一个位图,因此我们计算从 PDF 页面的尺寸(以点为单位)转换而来的位图所需的宽度和高度(以像素为单位)。 每个点是 1/72 英寸,所以我们基本上取图像的垂直或水平 DPI(在我们的示例中为 96),将其乘以相应的维度并除以 72。
接下来,我们使用刚刚计算的尺寸创建一个新的 PdfBitmap。 构造函数的最后一个参数告诉使用真彩色模式。
然后我们用白色填充整个位图并将页面渲染到它。 就这样!
/// <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);
}
}
}
此示例代码演示了如何使用 .Net PDF 库以编程方式填充 pdf 文档中的所有可编辑表单。
Patgames 支持服务就是您所说的“为开发者服务的开发者”。 当您获得产品许可时,您收到的不仅仅是一个很棒的库。 为了充分利用这一功能,您还可以直接从我们的 .Net 开发团队获得 12 个月的技术支持。
我已经尝试了你的最新版本,它运行良好——解决了我的两个问题! 感谢您满足我的要求——非常感谢。 我们仍将 [其他产品] 用于一些遗留项目,但我们已将其用于所有新项目。 尽管 [其他产品] 库本身很好,但我们发现它们的支持很差 - 毫无疑问,Pdfium.NET 支持已被证明要好得多,无论是速度还是质量! 再次感谢您提供一流的服务和优质的产品。 -TerryThe link is hidden due to ethical concerns.
Pdfium.Net SDK 的主要设计目标是使开发人员的事情变得简单直观。 类库抽象了使用底层 pdfium 库的所有细节,并提供了一个基于世界对象和其他直观类的接口。
此外,Pdfium.Net SDK 是有据可查的 SDK! 我们提供了丰富的文档,旨在让初学者和高级用户大致了解 Pdfium.Net SDK 的功能。
我们的目标之一是为开发人员提供高质量的工具,用于在 Microsoft Azure 等任何服务器系统上创建动态 PDF。
我已经验证您的 SDK 在部署到 Azure 时确实可以工作(我测试的几个产品没有 - 您可能想宣传这一点)。 我已经购买了。
再次感谢! -Cyberghttps://forum.patagames.com/posts/m1105-Workability-in-various-environments#post1105
赋予您的 .Net 应用查看 pdf 文件的能力! 借助多种视图模式、细致入微的自定义和对 acroforms pdf 查看器的完整支持,可无缝融入您的应用程序并根据您的设计量身定制。