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

如何将扫描PDF中带坐标的字符精准复刻至Word文档?

基于IronOCR字符坐标在Word中精准还原PDF排版

要实现精准还原,需要先解决坐标体系差异和单位转换问题,再通过Word的文本框控件定位每个字符,具体实现如下:

关键适配点

  • 坐标体系反转:PDF的Y轴原点在页面左下角,Word的Y轴原点在页面左上角,需用页面高度减去OCR返回的Y值得到Word中的实际Y位置
  • 单位转换:IronOCR返回的坐标为像素,Word定位使用磅(Point),标准转换公式:1像素 = 0.75磅(基于96DPI)

修改后的完整代码

//导入Iron Ocr库
using IronOcr;
//导入Microsoft Office库
using Microsoft.Office.Interop.Word;
using System;

class Program
{
    static void Main()
    {
        //以编程方式创建新Word文件
        Application wordApp = new Application();
        object missing = System.Reflection.Missing.Value;
        Document doc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
        
        //获取当前页面设置,用于坐标转换
        PageSetup pageSetup = doc.Sections[1].PageSetup;
        //计算页面有效高度(磅):页面总高度 - 上下边距
        double pageHeightInPoints = pageSetup.PageHeight - pageSetup.TopMargin - pageSetup.BottomMargin;
        //转换为像素(用于和OCR的Y坐标匹配)
        double pageHeightInPixels = pageHeightInPoints / 0.75;

        //创建Iron Tesseract实例
        var engine = new IronTesseract();
        //从PDF中提取所有文本字符
        var ocrResult = engine.Read("scanned.pdf");

        //遍历每个识别出的字符
        foreach (var chr in ocrResult.Characters)
        {
            //获取字符内容
            string character = chr.Text;
            //获取OCR返回的像素坐标
            double xPixel = chr.X;
            double yPixel = chr.Y;

            //1. 转换坐标到Word的磅单位
            double xPoint = xPixel * 0.75;
            //2. 反转Y轴坐标(PDF左下角→Word左上角)
            double yPoint = (pageHeightInPixels - yPixel) * 0.75;

            //创建文本框用于放置单个字符
            Shape textbox = doc.Shapes.AddTextbox(
                Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,
                xPoint + pageSetup.LeftMargin, //加上左边距,确保坐标基于页面
                yPoint + pageSetup.TopMargin,  //加上上边距
                chr.Width * 0.75, //字符宽度转磅
                chr.Height * 0.75 //字符高度转磅
            );

            //设置文本框内容
            textbox.TextFrame.TextRange.Text = character;

            //匹配OCR识别的字体属性
            textbox.TextFrame.TextRange.Font.Name = chr.FontName;
            textbox.TextFrame.TextRange.Font.Size = chr.FontSize;
            textbox.TextFrame.TextRange.Font.Bold = chr.IsBold ? 1 : 0;
            textbox.TextFrame.TextRange.Font.Italic = chr.IsItalic ? 1 : 0;

            //隐藏文本框边框,避免干扰排版
            textbox.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
        }

        //保存文档
        doc.SaveAs2("converted.docx");
        doc.Close();
        wordApp.Quit();
    }
}

额外注意事项

  • 如果OCR返回的DPI不是96,需要调整单位转换比例(公式:1像素 = 72 / DPI 磅)
  • 部分特殊字符可能需要额外处理编码兼容性
  • 批量处理大文档时,建议添加进度控制,避免Word进程卡顿

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 20:24:32