You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PDFsharp中Document.Save是否支持保存进度回调以显示进度条?

关于PDFsharp 1.32.2608.0保存进度回调的问题

结论

PDFsharp 1.32.2608.0版本的Document.Save方法没有内置回调函数用于追踪保存进度、更新进度条。这个版本的API设计中,Save是同步阻塞的操作,不提供进度报告机制。

替代实现方案

如果需要给用户展示保存进度,可尝试以下几种方式:

  • 拆分文档分批处理:如果你的PDF由多个独立部分(如章节、页面)组成,可以分阶段生成并保存。例如先生成前若干页面保存到临时PDF文件,再打开该文件追加后续页面,每完成一个阶段就更新进度条。示例代码思路:

    // 初始化临时文档
    PdfDocument tempDoc = new PdfDocument();
    int totalPages = 100; // 总页数
    int batchSize = 10; // 每批处理页数
    
    for (int i = 0; i < totalPages; i += batchSize)
    {
        // 生成当前批次的页面
        for (int j = i; j < Math.Min(i + batchSize, totalPages); j++)
        {
            PdfPage page = tempDoc.AddPage();
            // 绘制页面内容...
        }
    
        // 保存临时文档(首次直接写入,后续追加)
        if (i == 0)
            tempDoc.Save("temp.pdf");
        else
        {
            using (PdfDocument existingDoc = PdfDocument.Open("temp.pdf"))
            {
                foreach (PdfPage page in tempDoc.Pages)
                {
                    existingDoc.AddPage(page);
                }
                existingDoc.Save("temp.pdf");
            }
            tempDoc.Dispose();
            tempDoc = new PdfDocument();
        }
    
        // 更新进度条
        UpdateProgressBar((int)(((i + batchSize) / (double)totalPages) * 100));
    }
    
    // 重命名临时文件为最终文件
    File.Move("temp.pdf", "final.pdf");
    
  • 后台线程+估算进度:将Save操作放到后台线程(如.NET 3.5中的BackgroundWorker)执行,避免阻塞UI。根据文档总页数、元素数量等预先估算进度,假设每完成一页或一个元素就更新一次进度(属于近似值,但能给用户提供反馈)。示例思路:

    BackgroundWorker worker = new BackgroundWorker();
    worker.WorkerReportsProgress = true;
    worker.DoWork += (sender, e) =>
    {
        PdfDocument doc = e.Argument as PdfDocument;
        worker.ReportProgress(0);
        // 执行保存操作
        doc.Save("output.pdf");
        worker.ReportProgress(100);
    };
    worker.ProgressChanged += (sender, e) =>
    {
        // 更新UI进度条
        progressBar1.Value = e.ProgressPercentage;
    };
    worker.RunWorkerCompleted += (sender, e) =>
    {
        MessageBox.Show("保存完成");
    };
    
    // 启动后台任务
    worker.RunWorkerAsync(yourPdfDocument);
    
  • 考虑升级PDFsharp版本:如果项目允许,可尝试升级到PDFsharp的更高版本(如1.50系列),后续版本的API可能提供了异步保存或进度回调的支持,但需要确认版本是否兼容.NET Framework 3.5和Visual Studio 2008。


内容的提问来源于stack exchange,提问作者Gus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 02:06:25