Skip to main content
 首页 » 编程设计

c#之使用 Ghostscript 从 PDF 裁剪页脚

2024年02月06日33虾米姐

我正在尝试使用 Ghostscript 和 C# 裁剪 PDF 的底部一英寸。

当我运行我的代码时,它成功创建了新的 PDF,但它完全是空白的。我对 gsArgsList.Add("-c\"[/CropBox [0 72 0 0]/PAGES pdfmark\""); 的理解是将从底部裁剪 72pt(1 英寸)页面的。我已经包含了一些代码,希望有人能看到一些明显的东西。

我玩过 CropBox 的 4 个数字参数,但无论我传递什么,它总是生成空白 PDF。我只想删除页脚。

更新 - 我的代码现在显示了有效的解决方案。

/// <summary> 
/// Crop the bottom inch from the temporary PDF file using GhostScript. 
/// A new PDF file (test_cropped.pdf) will be created with the modifications. 
/// </summary> 
/// <param name="tempPDF">the path to the temporary PDF</param> 
/// <param name="croppedPDF">the path to the modified PDF</param> 
public static void cropPDFFooter(string inputPDF, string outputPDF, string pdfPostScript) 
{ 
     try 
        { 
            string gsPath = @"C:\gs\gs9.14\bin\gswin64c.exe"; 
 
            List<string> gsArgsList = new List<string>(); 
            gsArgsList.Add(" -o " + outputFile); 
            gsArgsList.Add(" -sDEVICE=pdfwrite"); 
            gsArgsList.Add(" -o " + outputFile + " -c \"mark /.HWMargins [ 0.0 288.0 0.0 0.0 ] .dicttomark setpagedevice\" -f " + inputFile + ""); 
 
            var gsArgs = String.Join(null, gsArgsList); 
 
            System.Diagnostics.Process.Start(gsPath, gsArgs); 
 
        } 
    catch (Exception ex) 
    { 
        Console.WriteLine(ex.ToString()); 
        Console.ReadLine(); 
    } 
} 

请您参考如下方法:

Ghostscript 还支持 .HWMargins [ lx by rx uy ] 这是一个由四个实数组成的数组,以点(1/72 英寸)为单位的边距。如果我这样做:

 gs -sDEVICE=pdfwrite -o x.pdf \ 
    -c "mark /.HWMargins [ 144.0 288.0 0.0 0.0 ] .dicttomark setpagedevice" \ 
    -f examples/annots.pdf 

然后输出裁剪了左边两英寸和底部 4 英寸。

请注意,这可以在 -c 之前与 -dPDFFitPage -dFIXEDMEDIA 一起使用,页面将适合(包括所有信息,包括页脚)页面更大的边距。

无法通过 Ghostscript (AFAIK) 一次性将页面调整为较小的尺寸并裁剪部分页面。