C# PDF 文档中的尖锐位置

标签 c# pdf pdfsharp

您好,我正在使用 PDF sharp 将用户输入打印到模板文档中的位置。

数据(字段)是从用户(网页)收集的,并使用拉绳方法写入文档的适当位置。

目前我正在通过反复试验找到每个页面中每个模板化字段的像素位置。如果有一种方法可以确定 pdf 页面中每个字段的像素位置,那将会容易得多。

任何建议都会很有帮助。

谢谢

最佳答案

我和你有同样的问题,josephj1989,我找到了我认为是我们的答案。

根据 this page在 PDFSharp 文档中,

The current implementation of PDFsharp has only one layout of the graphics context. The origin (0, 0) is top left and coordinates grow right and down. The unit of measure is always point (1/72 inch).

所以,假设我想在 8.5 x 11 页面的左侧 3 英寸处和顶部 7.5 英寸处绘制一个图像,那么我会这样做:

PdfDocument document = GetBlankPdfDocument();
PdfPage myPage = document.AddPage();
myPage.Orientation = PdfSharp.PageOrientation.Portrait;
myPage.Width = XUnit.FromInch(8.5);
myPage.Height = XUnit.FromInch(11);
XImage myImage = GetSampleImage();

double myX = 3 * 72;
double myY = 7.5 * 72;
double someWidth = 126;
double someHeight = 36;

XGraphics gfx = XGraphics.FromPdfPage(myPage);
gfx.DrawImage(myBarcode, myX, myY, someWidth, someHeight);

我自己用条形码图像对此进行了测试,我发现当您使用他们的公式来测量定位时,您可以获得 1/72 英寸的精度。这还不错。

因此,在这一点上,最好为此类测量创建某种封装,以便我们主要关注手头的任务,而不是转换的细节。

public static double GetCoordinateFromInch(double inches)
{
  return inches * 72;
}

我们可以继续以这种方式制作其他助手......

public static double GetCoordinateFromCentimeter(double centimeters)
{
  return centimeters * 0.39370 * 72;
}

有了这样的辅助方法,我们可以用前面的示例代码来做到这一点:

double myX = GetCoordinateFromInch(3);
double myY = GetCoordinateFromInch(7.5);
double someWidth = 126;
double someHeight = 36;

XGraphics gfx = XGraphics.FromPdfPage(myPage);
gfx.DrawImage(myBarcode, myX, myY, someWidth, someHeight);

希望对您有所帮助。我相信您会编写比我示例中的代码更清晰的代码。此外,可能有更智能的方法来简化此过程,但我只是想在这里放置一些可以立即使用我们在文档中看到的内容的东西。

愉快的 PDF 渲染!

关于C# PDF 文档中的尖锐位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13263252/

相关文章:

javascript - 现在的 ASP.NET Javascript 框架

c# - 转换到泛型时忽略 T

html - tinyMCE - 在移动设备上移动图像并调整其大小

c# - 如何绘制正方形并动态分配颜色属性(PDFsharp)?

c# - 在 Pdf 上绘制成窗口窗体 C# (visual studio 2015)

c# - mvvmcross iOS 绑定(bind)到列表无法将 `lambda expression' 转换为非委托(delegate)类型 `string'

java - X509Certificate 在 Java 中返回到 byte[],在 C# 中返回到 X509Certificate

excel - 使用 Interop.Excel 将 Excel 转换为 PDF 时不显示图像

c# - 在新浏览器选项卡中查看 PDF 文档

c# - PDFsharp:有没有办法在页面标题中生成 "Page X of Y"?