IRONSOFTWAREHOME
PDF 工具

如何在 Mac 和 Windows 上将网页另存为 PDF 文件

Curtis Chau
Curtis Chau
Updated: 2026年9月4日

IronPDF在C#中通过其直观API和基于Chrome的渲染引擎提供完整的PDF查看功能,而PDFSharp提供需要更复杂代码的基本开源PDF操作。

在软件开发中,处理各种格式的数据至关重要。 PDF(便携式文档格式)是一种广泛使用的文档共享标准。 在 C# 编程中,查看 PDF 对于创建专业文档管理数字内容至关重要。 IronPDF库提供了用于PDF生成和操作的完整工具。

C# 的多功能性使其在开发各种领域的应用程序方面广受欢迎。 PDF格式可确保文档完整性,并在不同平台上保持一致的呈现效果。 将 PDF 查看功能集成到您的应用程序中,可以改善用户体验简化工作流程,并为文档处理提供高效的解决方案。 对于需要从扫描文档中识别文本的应用,配套的 OCR 解决方案可以提高您的 PDF 处理能力。 IronPDF 文档提供了完整的实施指南。 处理安全文档时,正确的 PDF 处理至关重要。

本文探讨了使用C#查看PDF,介绍了两个库——PDFSharpIronPDF——并提供了安装和使用它们的说明。 您将研究影响您在这些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。 执行以下命令:

PM > 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:

PM > 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
    }
}

此代码使用PDFSharp读取和提取PDF文件中的文本。程序在导入模式下打开"output.pdf"并逐页迭代以提取内容。 与IronPDF 简单易用的 API不同,这种方法需要了解 PDF 的内部结构。 IronPDF 的文本提取示例展示了一种更简单的方法。

控制台窗口显示PDFSharp的基本文本提取尝试,输出为

为什么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需要更多的样板代码来完成如添加水印管理页面方向等常见任务。

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}");
        }
    }
}

此代码使用IronPDF从"ExtractAllText方法。 实现自动处理PDF的复杂性,相比于PDFSharp所需的手动解析,明显提供了优势。您的应用可以立即使用此功能,而无需了解PDF内部结构。 完整教程提供了更多示例。

IronPDF控制台窗口成功显示文本提取及

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();
    }
}

这些功能对于处理表单处理或满足合规性要求的企业应用程序至关重要。 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;
    }
}

这种方法利用现有的 HTML/CSS 技能并保持关注点分离,具有明显的优势。 该库通过其完整的 API 为您管理复杂性。

虽然这两个库各有优点,但 IronPDF 以其丰富的功能和简洁性脱颖而出。 性能基准测试表明,IronPDF 可以高效处理大型文档。 对于优先考虑长期可维护性的团队,IronPDF 提供完整的文档、专业的支持和丰富的代码示例

IronPDF 可免费用于开发用途,并提供免费试用版,供用户探索高级功能。 要了解有关查看 PDF 内容的更多信息,请访问提取文本和图像指南。 更多示例请参见IronPDF HTML 转 PDF 代码示例。 您的应用程序可以立即受益于 IronPDF 的现代化架构和完整功能。

请注意: PDFSharp 是其各自所有者的注册商标。 本网站与PDFSharp无任何关联,亦未获得其认可或赞助。所有产品名称、标识和品牌均为其各自所有者的财产。 比较仅供参考,反映撰写时公开可用的信息。
Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

...
阅读更多

相关文章

Key in blue circle

立即获取免费的 30 天试用版密钥

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
预约您的免费现场演示
Booking Badge

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥
无需信用卡或创建账户