如何在 Mac 和 Windows 上将网页另存为 PDF 文件
IronPDF在C#中通过其直观API和基于Chrome的渲染引擎提供完整的PDF查看功能,而PDFSharp提供需要更复杂代码的基本开源PDF操作。
在软件开发中,处理各种格式的数据至关重要。 PDF(便携式文档格式)是一种广泛使用的文档共享标准。 在 C# 编程中,查看 PDF 对于创建专业文档和管理数字内容至关重要。 IronPDF库提供了用于PDF生成和操作的完整工具。
C# 的多功能性使其在开发各种领域的应用程序方面广受欢迎。 PDF格式可确保文档完整性,并在不同平台上保持一致的呈现效果。 将 PDF 查看功能集成到您的应用程序中,可以改善用户体验,简化工作流程,并为文档处理提供高效的解决方案。 对于需要从扫描文档中识别文本的应用,配套的 OCR 解决方案可以提高您的 PDF 处理能力。 IronPDF 文档提供了完整的实施指南。 处理安全文档时,正确的 PDF 处理至关重要。
本文探讨了使用C#查看PDF,介绍了两个库——PDFSharp和IronPDF——并提供了安装和使用它们的说明。 您将研究影响您在这些PDF 生成解决方案之间做出选择的架构差异、代码复杂性和维护考虑因素。 对于需要文档安全性的环境而言,了解这些差异至关重要。 IronPDF 演示展示了实际应用,而API 参考提供了详细的规范。
什么是PDFSharp及其PDF查看处理方式?
PDFSharp是一个为C#提供PDF操作工具包的开源库。 与IronPDF的基于Chrome的渲染引擎不同,PDFSharp基于低级绘图模型操作,提供对PDF原语的直接控制。 该库使您能够访问和操作PDF 文档结构。 然而,与IronPDF的完整功能相比,PDFSharp对于常见任务需要大大更多的手工编码。
PDFSharp的架构遵循文档对象模型方法,您可以直接与PDF对象进行交互。 这与IronPDF 的 HTML 到 PDF 转换方法不同,后者使用 Web 技术生成文档。 虽然PDFSharp在创建空白PDF和绘图操作方面表现出色,但对于添加页眉或嵌入图像等任务,则需要更多代码。 高级功能如JavaScript渲染、响应式CSS支持和网络字体集成在PDFSharp中不可用。
如何在Visual Studio中安装PDFSharp?
与IronPDF的安装过程类似,可以使用NuGet安装PDFSharp。 执行以下命令:
Install-Package PdfSharp
此命令为您的项目安装PDFSharp库。 不同于IronPDF的高级安装选项,PDFSharp缺乏对Docker容器或Linux部署的内置支持。 快速入门指南提供了 IronPDF 的更多设置说明。
PDFSharp的系统需求是什么?
PDFSharp目标的是较旧的.NET Framework版本,可能会在较新的.NET版本和云环境中遇到兼容性问题。 与 IronPDF 的自动平台检测功能不同,该库需要手动配置才能进行跨平台部署。 内存使用模式不同,PDFSharp在处理复杂操作时可能消耗更多资源。 在高性能应用场景下,这些差异会变得很明显。 IronPDF性能指南提供了PDFSharp无法获得的优化策略。
为什么PDFSharp架构影响性能?
PDFSharp的低级架构通过需要更多CPU周期的直接PDF对象操作影响性能。 该库缺乏针对批量处理、并行操作或异步工作流的优化。 由于需要人工操作员解析,复杂文档的文本提取性能会下降。 IronPDF 基于 Chrome 的引擎采用浏览器优化技术,从而实现更快的渲染速度和更高的内存效率。 对于异步操作,IronPDF 的架构提供了显著优势。
为什么 IronPDF 是更好的 PDF 查看选择?
IronPDF是一个功能丰富的库,使您能够轻松处理 PDF 操作。 IronPDF 设计简洁且功能多样,允许您在应用程序中创建、编辑和阅读 PDF 文档。 除了基本功能外,IronPDF 还提供HTML 转 PDF 、支持各种图像格式以及高效处理PDF 操作等高级功能。 该库擅长生成 PDF 报告和转换不同的文件格式。
IronPDF 的架构基础采用Chrome 渲染引擎,确保网页内容的像素级完美渲染。 这种方法简化了诸如管理字体、处理 JavaScript和支持 UTF-8 字符等常见任务。 该库支持线性化、 PDF压缩、数字签名和注释。
IronPDF 可以处理 PDF 文件并格式化数据,支持元数据提取和异步操作。 对于Blazor 应用程序,IronPDF 提供流畅的集成。
如何在我的项目中安装 IronPDF?
using NuGet 程序包管理器或程序包管理器控制台安装 IronPDF:
Install-Package IronPdf
此命令安装 IronPDF 及其依赖项。 对于Docker 部署或Linux 环境,可能需要额外的软件包。 快速入门指南提供了设置说明。
IronPDF 的 API 设计有哪些优越之处?
IronPDF 的 API 遵循现代 .NET 模式,具有流畅的接口和异步支持。 该库提供直观的方法名称和完整的IntelliSense文档。 错误信息提供了可操作的解决方案,加快了开发速度。 API 参考文档提供了完整的方法详情。
何时应该使用 IronPDF 的 Chrome 渲染引擎?
using IronPDF 的 Chrome 引擎转换响应式 HTML 布局、渲染 JavaScript 内容或处理现代 CSS 设计。 该引擎可自动处理网页字体、SVG 图形和 Canvas 元素。 它非常适合使用 HTML 模板生成发票或创建带有可视化效果的报告。 对于WebGL 内容的渲染,该引擎提供 GPU 加速。
如何使用PDFSharp查看PDF内容?
本节演示了使用PDFSharp查看PDF文件。由于其低级性质,PDFSharp中的文本提取相对于IronPDF的简单方法来说比较复杂:
using System;
using System.Text;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.Content;
using PdfSharp.Pdf.Content.Objects;
class Program
{
static void Main()
{
// Specify the path to the PDF file
string pdfFilePath = "output.pdf";
// Open the PDF document in import mode
// Note: PDFsharp requires specific open modes for different operations
PdfDocument document = PdfReader.Open(pdfFilePath, PdfDocumentOpenMode.Import);
// Create StringBuilder for extracted text
// This approach is less efficient than IronPDF's built-in methods
StringBuilder extractedText = new StringBuilder();
// Iterate through each page of the document
for (int pageIndex = 0; pageIndex < document.PageCount; pageIndex++)
{
// Get the current page
PdfPage page = document.Pages[pageIndex];
// Extract text using content reader (simplified approach)
// Real implementation requires extensive operator parsing
CObject content = ContentReader.ReadContent(page);
// Parse content objects to extract text
// This is where PDFsharp becomes significantly complex
ExtractText(content, extractedText);
// Note: Actual text extraction requires parsing operators
// This is a simplified representation
Console.WriteLine($"Page {pageIndex + 1} processed");
}
Console.WriteLine("Extracted Text: " + extractedText.ToString());
Console.ReadLine(); // Wait for user input before closing the console
}
static void ExtractText(CObject content, StringBuilder text)
{
// PDFsharp requires manual parsing of content streams
// This is significantly more complex than shown here
// Real implementation would need to handle:
// - Text operators (Tj, TJ, ', ", etc.)
// - Font encoding and character mapping
// - Text positioning and transformation matrices
// - Unicode mapping and glyph substitution
// - Whitespace detection and word boundaries
if (content is CArray array)
{
foreach (var item in array)
{
ExtractText(item, text);
}
}
else if (content is CString str)
{
// Simplified text extraction - real implementation needs encoding handling
text.Append(str.Value);
}
// Additional operators would need handling for complete extraction
}
}
using System;
using System.Text;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.Content;
using PdfSharp.Pdf.Content.Objects;
class Program
{
static void Main()
{
// Specify the path to the PDF file
string pdfFilePath = "output.pdf";
// Open the PDF document in import mode
// Note: PDFsharp requires specific open modes for different operations
PdfDocument document = PdfReader.Open(pdfFilePath, PdfDocumentOpenMode.Import);
// Create StringBuilder for extracted text
// This approach is less efficient than IronPDF's built-in methods
StringBuilder extractedText = new StringBuilder();
// Iterate through each page of the document
for (int pageIndex = 0; pageIndex < document.PageCount; pageIndex++)
{
// Get the current page
PdfPage page = document.Pages[pageIndex];
// Extract text using content reader (simplified approach)
// Real implementation requires extensive operator parsing
CObject content = ContentReader.ReadContent(page);
// Parse content objects to extract text
// This is where PDFsharp becomes significantly complex
ExtractText(content, extractedText);
// Note: Actual text extraction requires parsing operators
// This is a simplified representation
Console.WriteLine($"Page {pageIndex + 1} processed");
}
Console.WriteLine("Extracted Text: " + extractedText.ToString());
Console.ReadLine(); // Wait for user input before closing the console
}
static void ExtractText(CObject content, StringBuilder text)
{
// PDFsharp requires manual parsing of content streams
// This is significantly more complex than shown here
// Real implementation would need to handle:
// - Text operators (Tj, TJ, ', ", etc.)
// - Font encoding and character mapping
// - Text positioning and transformation matrices
// - Unicode mapping and glyph substitution
// - Whitespace detection and word boundaries
if (content is CArray array)
{
foreach (var item in array)
{
ExtractText(item, text);
}
}
else if (content is CString str)
{
// Simplified text extraction - real implementation needs encoding handling
text.Append(str.Value);
}
// Additional operators would need handling for complete extraction
}
}
Imports System
Imports System.Text
Imports PdfSharp.Pdf
Imports PdfSharp.Pdf.IO
Imports PdfSharp.Pdf.Content
Imports PdfSharp.Pdf.Content.Objects
Class Program
Shared Sub Main()
' Specify the path to the PDF file
Dim pdfFilePath As String = "output.pdf"
' Open the PDF document in import mode
' Note: PDFsharp requires specific open modes for different operations
Dim document As PdfDocument = PdfReader.Open(pdfFilePath, PdfDocumentOpenMode.Import)
' Create StringBuilder for extracted text
' This approach is less efficient than IronPDF's built-in methods
Dim extractedText As New StringBuilder()
' Iterate through each page of the document
For pageIndex As Integer = 0 To document.PageCount - 1
' Get the current page
Dim page As PdfPage = document.Pages(pageIndex)
' Extract text using content reader (simplified approach)
' Real implementation requires extensive operator parsing
Dim content As CObject = ContentReader.ReadContent(page)
' Parse content objects to extract text
' This is where PDFsharp becomes significantly complex
ExtractText(content, extractedText)
' Note: Actual text extraction requires parsing operators
' This is a simplified representation
Console.WriteLine($"Page {pageIndex + 1} processed")
Next
Console.WriteLine("Extracted Text: " & extractedText.ToString())
Console.ReadLine() ' Wait for user input before closing the console
End Sub
Shared Sub ExtractText(content As CObject, text As StringBuilder)
' PDFsharp requires manual parsing of content streams
' This is significantly more complex than shown here
' Real implementation would need to handle:
' - Text operators (Tj, TJ, ', ", etc.)
' - Font encoding and character mapping
' - Text positioning and transformation matrices
' - Unicode mapping and glyph substitution
' - Whitespace detection and word boundaries
If TypeOf content Is CArray Then
Dim array As CArray = CType(content, CArray)
For Each item In array
ExtractText(item, text)
Next
ElseIf TypeOf content Is CString Then
Dim str As CString = CType(content, CString)
' Simplified text extraction - real implementation needs encoding handling
text.Append(str.Value)
End If
' Additional operators would need handling for complete extraction
End Sub
End Class
此代码使用PDFSharp读取和提取PDF文件中的文本。程序在导入模式下打开"output.pdf"并逐页迭代以提取内容。 与IronPDF 简单易用的 API不同,这种方法需要了解 PDF 的内部结构。 IronPDF 的文本提取示例展示了一种更简单的方法。

为什么PDFSharp文本提取更复杂?
PDFSharp的复杂性来自于其低级方法。 与IronPDF的高级API不同,PDFSharp要求您了解包括操作符、编码和内容流的PDF内部结构:
// PDFsharp: Complex font handling and text positioning
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
// Must manually specify fonts and handle font embedding
XFont font = new XFont("Arial", 12, XFontStyle.Regular);
// Manual text positioning with exact coordinates
gfx.DrawString("Hello World", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
// Must handle coordinate transformations manually
gfx.TranslateTransform(100, 200);
gfx.RotateTransform(45);
gfx.DrawString("Rotated Text", font, XBrushes.Red, 0, 0);
// IronPDF: Simple HTML approach with CSS styling
var renderer = new ChromePdfRenderer();
var doc = renderer.RenderHtmlAsPdf(@"
<h1 style='text-align: center;'>Hello World</h1>
<p style='transform: rotate(45deg); margin-left: 100px; margin-top: 200px; color: red;'>
Rotated Text
</p>");
// IronPDF automatically handles fonts, positioning, and transformations
// PDFsharp: Complex font handling and text positioning
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
// Must manually specify fonts and handle font embedding
XFont font = new XFont("Arial", 12, XFontStyle.Regular);
// Manual text positioning with exact coordinates
gfx.DrawString("Hello World", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
// Must handle coordinate transformations manually
gfx.TranslateTransform(100, 200);
gfx.RotateTransform(45);
gfx.DrawString("Rotated Text", font, XBrushes.Red, 0, 0);
// IronPDF: Simple HTML approach with CSS styling
var renderer = new ChromePdfRenderer();
var doc = renderer.RenderHtmlAsPdf(@"
<h1 style='text-align: center;'>Hello World</h1>
<p style='transform: rotate(45deg); margin-left: 100px; margin-top: 200px; color: red;'>
Rotated Text
</p>");
// IronPDF automatically handles fonts, positioning, and transformations
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Imports IronPdf
' PDFsharp: Complex font handling and text positioning
Dim document As New PdfDocument()
Dim page As PdfPage = document.AddPage()
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
' Must manually specify fonts and handle font embedding
Dim font As New XFont("Arial", 12, XFontStyle.Regular)
' Manual text positioning with exact coordinates
gfx.DrawString("Hello World", font, XBrushes.Black, New XRect(0, 0, page.Width, page.Height), XStringFormats.Center)
' Must handle coordinate transformations manually
gfx.TranslateTransform(100, 200)
gfx.RotateTransform(45)
gfx.DrawString("Rotated Text", font, XBrushes.Red, 0, 0)
' IronPDF: Simple HTML approach with CSS styling
Dim renderer As New ChromePdfRenderer()
Dim doc = renderer.RenderHtmlAsPdf("
<h1 style='text-align: center;'>Hello World</h1>
<p style='transform: rotate(45deg); margin-left: 100px; margin-top: 200px; color: red;'>
Rotated Text
</p>")
' IronPDF automatically handles fonts, positioning, and transformations
这种建筑结构上的差异对维护工作产生了重大影响。 PDFSharp需要更多的样板代码来完成如添加水印或管理页面方向等常见任务。
PDFSharp在查看PDF时的限制是什么?
在满足现代PDF需求时,PDFSharp的限制变得明显:
1.不支持 HTML 转 PDF :无法直接转换 HTML 代码。 2.复杂文本提取:需要了解 PDF 运算符 3.图像支持有限:需要手动缩放和定位。 4.无内置OCR :缺乏OCR功能 5.缺少高级功能:不支持数字签名或 PDF/A 合规性
PDFSharp如何处理内存和性能?
PDFSharp将整个PDF加载到内存中,可能导致大文件的问题。 流处理尚未完全支持,限制了可扩展性。 不同于IronPDF的改进渲染流水线,PDFSharp缺乏内置的缓存机制。 性能优化指南提供了PDFSharp所没有的策略。
IronPDF如何简化C#中的PDF查看?
using IronPDF 查看 PDF 文件只需要几行代码。 该库会自动管理基本 URL 和资源编码:
using IronPdf;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Load the PDF document with error handling
var pdf = PdfDocument.FromFile("output.pdf");
// Extract all the text content from the PDF
string text = pdf.ExtractAllText();
// Print the extracted text to the console
Console.WriteLine("Full document text:");
Console.WriteLine(text);
// Additional extraction options demonstrating IronPDF's versatility
// Extract text from specific pages with formatting preserved
string pageText = pdf.ExtractTextFromPage(0);
Console.WriteLine($"\nPage 1 text: {pageText}");
// Extract all images and save them
var images = pdf.ExtractAllImages();
for (int i = 0; i < images.Count; i++)
{
images[i].SaveAs($"extracted_image_{i}.png");
}
// Access complete metadata
string author = pdf.MetaData.Author;
string title = pdf.MetaData.Title;
string subject = pdf.MetaData.Subject;
DateTime creationDate = pdf.MetaData.CreationDate;
Console.WriteLine($"\nDocument Info:");
Console.WriteLine($"Title: {title}");
Console.WriteLine($"Author: {author}");
Console.WriteLine($"Created: {creationDate}");
// Search for specific text
var searchResults = pdf.Search("invoice");
foreach (var result in searchResults)
{
Console.WriteLine($"Found '{result.Text}' on page {result.PageIndex}");
}
// Extract form field data
var form = pdf.Form;
foreach (var field in form.Fields)
{
Console.WriteLine($"Field: {field.Name} = {field.Value}");
}
}
}
using IronPdf;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Load the PDF document with error handling
var pdf = PdfDocument.FromFile("output.pdf");
// Extract all the text content from the PDF
string text = pdf.ExtractAllText();
// Print the extracted text to the console
Console.WriteLine("Full document text:");
Console.WriteLine(text);
// Additional extraction options demonstrating IronPDF's versatility
// Extract text from specific pages with formatting preserved
string pageText = pdf.ExtractTextFromPage(0);
Console.WriteLine($"\nPage 1 text: {pageText}");
// Extract all images and save them
var images = pdf.ExtractAllImages();
for (int i = 0; i < images.Count; i++)
{
images[i].SaveAs($"extracted_image_{i}.png");
}
// Access complete metadata
string author = pdf.MetaData.Author;
string title = pdf.MetaData.Title;
string subject = pdf.MetaData.Subject;
DateTime creationDate = pdf.MetaData.CreationDate;
Console.WriteLine($"\nDocument Info:");
Console.WriteLine($"Title: {title}");
Console.WriteLine($"Author: {author}");
Console.WriteLine($"Created: {creationDate}");
// Search for specific text
var searchResults = pdf.Search("invoice");
foreach (var result in searchResults)
{
Console.WriteLine($"Found '{result.Text}' on page {result.PageIndex}");
}
// Extract form field data
var form = pdf.Form;
foreach (var field in form.Fields)
{
Console.WriteLine($"Field: {field.Name} = {field.Value}");
}
}
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Module Program
Sub Main()
' Load the PDF document with error handling
Dim pdf = PdfDocument.FromFile("output.pdf")
' Extract all the text content from the PDF
Dim text As String = pdf.ExtractAllText()
' Print the extracted text to the console
Console.WriteLine("Full document text:")
Console.WriteLine(text)
' Additional extraction options demonstrating IronPDF's versatility
' Extract text from specific pages with formatting preserved
Dim pageText As String = pdf.ExtractTextFromPage(0)
Console.WriteLine(vbCrLf & "Page 1 text: " & pageText)
' Extract all images and save them
Dim images = pdf.ExtractAllImages()
For i As Integer = 0 To images.Count - 1
images(i).SaveAs($"extracted_image_{i}.png")
Next
' Access complete metadata
Dim author As String = pdf.MetaData.Author
Dim title As String = pdf.MetaData.Title
Dim subject As String = pdf.MetaData.Subject
Dim creationDate As DateTime = pdf.MetaData.CreationDate
Console.WriteLine(vbCrLf & "Document Info:")
Console.WriteLine("Title: " & title)
Console.WriteLine("Author: " & author)
Console.WriteLine("Created: " & creationDate)
' Search for specific text
Dim searchResults = pdf.Search("invoice")
For Each result In searchResults
Console.WriteLine($"Found '{result.Text}' on page {result.PageIndex}")
Next
' Extract form field data
Dim form = pdf.Form
For Each field In form.Fields
Console.WriteLine($"Field: {field.Name} = {field.Value}")
Next
End Sub
End Module
此代码使用IronPDF从"ExtractAllText方法。 实现自动处理PDF的复杂性,相比于PDFSharp所需的手动解析,明显提供了优势。您的应用可以立即使用此功能,而无需了解PDF内部结构。 完整教程提供了更多示例。

IronPDF提供哪些高级PDF查看功能?
IronPDF 提供完整的 PDF 分析工具:
// Advanced PDF analysis with IronPDF
var pdf = PdfDocument.FromFile("complex-document.pdf");
// Extract structured content with detailed information
foreach (var page in pdf.Pages)
{
// Get page dimensions for layout analysis
var width = page.Width;
var height = page.Height;
var rotation = page.Rotation;
// Extract form fields with type information
var formFields = page.GetFormFields();
foreach (var field in formFields)
{
Console.WriteLine($"Field: {field.Name}, Type: {field.Type}, Value: {field.Value}");
}
// Extract annotations with properties
var annotations = page.GetAnnotations();
foreach (var annotation in annotations)
{
Console.WriteLine($"Annotation: {annotation.Title} - {annotation.Content}");
}
// Extract hyperlinks with destinations
var links = page.GetLinks();
foreach (var link in links)
{
Console.WriteLine($"Link: {link.Text} -> {link.Url}");
}
}
// Advanced search functionality with context
var searchResults = pdf.Search("invoice", SearchOptions.CaseInsensitive | SearchOptions.WholeWord);
foreach (var result in searchResults)
{
Console.WriteLine($"Found on page {result.PageIndex} at position {result.Position}: {result.Text}");
// Get surrounding text for context
string context = pdf.ExtractTextFromPage(result.PageIndex)
.Substring(Math.Max(0, result.Position - 50), 100);
Console.WriteLine($"Context: ...{context}...");
}
// Extract tables as structured data
var tables = pdf.ExtractTables();
foreach (var table in tables)
{
for (int row = 0; row < table.RowCount; row++)
{
for (int col = 0; col < table.ColumnCount; col++)
{
Console.Write($"{table[row, col]}\t");
}
Console.WriteLine();
}
}
// Advanced PDF analysis with IronPDF
var pdf = PdfDocument.FromFile("complex-document.pdf");
// Extract structured content with detailed information
foreach (var page in pdf.Pages)
{
// Get page dimensions for layout analysis
var width = page.Width;
var height = page.Height;
var rotation = page.Rotation;
// Extract form fields with type information
var formFields = page.GetFormFields();
foreach (var field in formFields)
{
Console.WriteLine($"Field: {field.Name}, Type: {field.Type}, Value: {field.Value}");
}
// Extract annotations with properties
var annotations = page.GetAnnotations();
foreach (var annotation in annotations)
{
Console.WriteLine($"Annotation: {annotation.Title} - {annotation.Content}");
}
// Extract hyperlinks with destinations
var links = page.GetLinks();
foreach (var link in links)
{
Console.WriteLine($"Link: {link.Text} -> {link.Url}");
}
}
// Advanced search functionality with context
var searchResults = pdf.Search("invoice", SearchOptions.CaseInsensitive | SearchOptions.WholeWord);
foreach (var result in searchResults)
{
Console.WriteLine($"Found on page {result.PageIndex} at position {result.Position}: {result.Text}");
// Get surrounding text for context
string context = pdf.ExtractTextFromPage(result.PageIndex)
.Substring(Math.Max(0, result.Position - 50), 100);
Console.WriteLine($"Context: ...{context}...");
}
// Extract tables as structured data
var tables = pdf.ExtractTables();
foreach (var table in tables)
{
for (int row = 0; row < table.RowCount; row++)
{
for (int col = 0; col < table.ColumnCount; col++)
{
Console.Write($"{table[row, col]}\t");
}
Console.WriteLine();
}
}
Imports System
Imports IronPdf
' Advanced PDF analysis with IronPDF
Dim pdf = PdfDocument.FromFile("complex-document.pdf")
' Extract structured content with detailed information
For Each page In pdf.Pages
' Get page dimensions for layout analysis
Dim width = page.Width
Dim height = page.Height
Dim rotation = page.Rotation
' Extract form fields with type information
Dim formFields = page.GetFormFields()
For Each field In formFields
Console.WriteLine($"Field: {field.Name}, Type: {field.Type}, Value: {field.Value}")
Next
' Extract annotations with properties
Dim annotations = page.GetAnnotations()
For Each annotation In annotations
Console.WriteLine($"Annotation: {annotation.Title} - {annotation.Content}")
Next
' Extract hyperlinks with destinations
Dim links = page.GetLinks()
For Each link In links
Console.WriteLine($"Link: {link.Text} -> {link.Url}")
Next
Next
' Advanced search functionality with context
Dim searchResults = pdf.Search("invoice", SearchOptions.CaseInsensitive Or SearchOptions.WholeWord)
For Each result In searchResults
Console.WriteLine($"Found on page {result.PageIndex} at position {result.Position}: {result.Text}")
' Get surrounding text for context
Dim context As String = pdf.ExtractTextFromPage(result.PageIndex).Substring(Math.Max(0, result.Position - 50), 100)
Console.WriteLine($"Context: ...{context}...")
Next
' Extract tables as structured data
Dim tables = pdf.ExtractTables()
For Each table In tables
For row As Integer = 0 To table.RowCount - 1
For col As Integer = 0 To table.ColumnCount - 1
Console.Write($"{table(row, col)}" & vbTab)
Next
Console.WriteLine()
Next
Next
这些功能对于处理表单处理或满足合规性要求的企业应用程序至关重要。 IronPDF 支持PDF/A 转换和PDF/UA 无障碍标准。
什么时候我应该选择IronPDF而不是PDFSharp用于PDF查看?
您在IronPDF和PDFSharp之间的选择取决于您的项目需求:
在以下情况下选择 IronPDF: 您需要将 HTML 转换为 PDF。
考虑使用PDFSharp当:
- 构建简单的 PDF 生成工具
- 使用静态布局 预算限制阻碍了商业许可。
IronPDF 如何处理大规模 PDF 处理?
IronPDF凭借其内置的优化功能,在企业级处理方面表现出色。 该库支持并行处理、批量操作和内存高效的流式传输。 异步方法使 Web 应用程序能够执行非阻塞操作。 IronPDF 的 Chrome 引擎能够高效地处理并发请求,使其适用于微服务和无服务器功能。
我的C#项目应该选择哪个PDF库?
PDFSharp和IronPDF都为寻找多功能解决方案的开发者提供了功能。 PDFSharp提供一种适用于基本PDF任务的轻量工具包。 相比之下,IronPDF 是为完整的 PDF 操作而设计的。 其先进的功能使其能够有效地处理复杂的 PDF 操作。
以下代码示例展示了 IronPDF 简洁的架构:
// IronPDF: Clean, maintainable code following SOLID principles
public class InvoiceService
{
private readonly ITemplateEngine _templateEngine;
private readonly IConfiguration _config;
public async Task<byte[]> GenerateInvoicePdf(Invoice invoice)
{
// Render HTML from template with full CSS support
var html = await _templateEngine.RenderAsync("invoice.html", invoice);
// Configure rendering with fluent API
var renderer = new ChromePdfRenderer
{
RenderingOptions = new ChromePdfRenderOptions
{
MarginTop = 50,
MarginBottom = 50,
PaperSize = PdfPaperSize.A4,
Title = $"Invoice #{invoice.Number}",
// Enable JavaScript for dynamic content
EnableJavaScript = true,
// Wait for AJAX calls to complete
WaitFor = WaitFor.NetworkIdle0,
// Custom headers and footers
HtmlHeader = "<div style='text-align: center;'>{page} of {total-pages}</div>",
HtmlFooter = "<div style='text-align: center;'>© 2024 Your Company</div>"
}
};
// Render with full Chrome engine support
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
// Add security features
pdf.SecuritySettings.SetPassword("user-password", "owner-password");
pdf.SecuritySettings.AllowPrinting = true;
pdf.SecuritySettings.AllowCopy = false;
// Add digital signature for authenticity
pdf.SignWithCertificate(certificate, "Authorized Signature");
// Improve for web delivery
pdf.CompressImages(90);
return pdf.BinaryData;
}
}
// IronPDF: Clean, maintainable code following SOLID principles
public class InvoiceService
{
private readonly ITemplateEngine _templateEngine;
private readonly IConfiguration _config;
public async Task<byte[]> GenerateInvoicePdf(Invoice invoice)
{
// Render HTML from template with full CSS support
var html = await _templateEngine.RenderAsync("invoice.html", invoice);
// Configure rendering with fluent API
var renderer = new ChromePdfRenderer
{
RenderingOptions = new ChromePdfRenderOptions
{
MarginTop = 50,
MarginBottom = 50,
PaperSize = PdfPaperSize.A4,
Title = $"Invoice #{invoice.Number}",
// Enable JavaScript for dynamic content
EnableJavaScript = true,
// Wait for AJAX calls to complete
WaitFor = WaitFor.NetworkIdle0,
// Custom headers and footers
HtmlHeader = "<div style='text-align: center;'>{page} of {total-pages}</div>",
HtmlFooter = "<div style='text-align: center;'>© 2024 Your Company</div>"
}
};
// Render with full Chrome engine support
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
// Add security features
pdf.SecuritySettings.SetPassword("user-password", "owner-password");
pdf.SecuritySettings.AllowPrinting = true;
pdf.SecuritySettings.AllowCopy = false;
// Add digital signature for authenticity
pdf.SignWithCertificate(certificate, "Authorized Signature");
// Improve for web delivery
pdf.CompressImages(90);
return pdf.BinaryData;
}
}
Imports System.Threading.Tasks
' IronPDF: Clean, maintainable code following SOLID principles
Public Class InvoiceService
Private ReadOnly _templateEngine As ITemplateEngine
Private ReadOnly _config As IConfiguration
Public Async Function GenerateInvoicePdf(invoice As Invoice) As Task(Of Byte())
' Render HTML from template with full CSS support
Dim html = Await _templateEngine.RenderAsync("invoice.html", invoice)
' Configure rendering with fluent API
Dim renderer = New ChromePdfRenderer With {
.RenderingOptions = New ChromePdfRenderOptions With {
.MarginTop = 50,
.MarginBottom = 50,
.PaperSize = PdfPaperSize.A4,
.Title = $"Invoice #{invoice.Number}",
' Enable JavaScript for dynamic content
.EnableJavaScript = True,
' Wait for AJAX calls to complete
.WaitFor = WaitFor.NetworkIdle0,
' Custom headers and footers
.HtmlHeader = "<div style='text-align: center;'>{page} of {total-pages}</div>",
.HtmlFooter = "<div style='text-align: center;'>© 2024 Your Company</div>"
}
}
' Render with full Chrome engine support
Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html)
' Add security features
pdf.SecuritySettings.SetPassword("user-password", "owner-password")
pdf.SecuritySettings.AllowPrinting = True
pdf.SecuritySettings.AllowCopy = False
' Add digital signature for authenticity
pdf.SignWithCertificate(certificate, "Authorized Signature")
' Improve for web delivery
pdf.CompressImages(90)
Return pdf.BinaryData
End Function
End Class
这种方法利用现有的 HTML/CSS 技能并保持关注点分离,具有明显的优势。 该库通过其完整的 API 为您管理复杂性。
虽然这两个库各有优点,但 IronPDF 以其丰富的功能和简洁性脱颖而出。 性能基准测试表明,IronPDF 可以高效处理大型文档。 对于优先考虑长期可维护性的团队,IronPDF 提供完整的文档、专业的支持和丰富的代码示例。
IronPDF 可免费用于开发用途,并提供免费试用版,供用户探索高级功能。 要了解有关查看 PDF 内容的更多信息,请访问提取文本和图像指南。 更多示例请参见IronPDF HTML 转 PDF 代码示例。 您的应用程序可以立即受益于 IronPDF 的现代化架构和完整功能。
常见问题解答
在 C# 应用程序中查看 PDF 有哪些好处?
在 C# 应用程序中查看 PDF 可以通过提供标准化的文档格式来提升用户体验,这种格式易于导航和操作。像 IronPDF 这样的库为开发人员提供了无缝集成 PDF 查看功能的工具,从而简化工作流程并提高效率。
如何在 C# 中查看 PDF 文档?
您可以通过使用像 IronPDF 这样的库在 C# 中查看 PDF 文档。它允许您通过提供加载和呈现 PDF 文件的方法,将 PDF 查看功能无缝集成到您的 C# 项目中。
如何选择 C# 中用于 PDF 操作的合适库?
在选择 C# 中用于 PDF 操作的库时,请考虑功能集、易用性和对高级功能的支持等因素。推荐使用 IronPDF,因为它提供了全面的解决方案,包括 HTML 转 PDF 转换和对各种图像格式的支持,这可以简化复杂的 PDF 任务。
我可以使用 C# 库修改 PDF 吗?
是的,您可以使用像 IronPDF 这样的库在 C# 中修改 PDF。它提供了强大的工具来编辑和操作 PDF 文档,使开发人员能够高效地在 PDF 文件中添加、删除或更新内容。
如何在 C# 项目中安装 PDF 库?
要在 C# 项目中安装 PDF 库,如 IronPDF,请使用 NuGet 包管理器并在包管理器控制台中运行命令Install-Package IronPDF。此命令将把库及其依赖项添加到您的项目中。
在 C# 的 PDF 库中我应该寻找什么功能?
选择 C# 的 PDF 库时,要寻找 PDF 查看、编辑、HTML 转 PDF 转换以及对各种图像格式的支持等功能。IronPDF 提供了丰富的功能集,可以满足这些需求,为 PDF 处理提供了多功能的解决方案。
是否有 C# PDF 库的免费试用版?
是的,IronPDF 为开发人员提供免费试用,让您探索其高级 PDF 功能。这使您可以在购买之前测试库的功能并将其功能集成到您的 C# 项目中。
如何使用 C# 库从 PDF 中提取文本?
要使用 IronPDF 在 C# 中从 PDF 提取文本,请使用PdfDocument.FromFile()加载 PDF 文档,然后使用ExtractAllText()检索文本内容。这种简单的方法展示了 IronPDF 处理 PDF 文本提取的便捷性。
在哪里可以找到更多有关使用 PDF 的 C# 代码示例?
可以在 'IronPDF HTML to PDF Code Examples' 页面上找到有关使用 IronPDF 在 C# 中处理 PDF 的更多代码示例。此资源提供了实用的实现和集成 IronPDF 功能到您的 C# 项目的见解。
是什么让 IronPDF 成为 C# 中处理 PDF 的推荐选择?
IronPDF 因其广泛的功能集、简单性和多样性而受到推荐。它提供了高级 PDF 功能的全面解决方案,使其成为希望在 C# 应用程序中集成高级 PDF 功能的开发人员的首选。


