PDFsharp 添加 link 无效

PDFsharp adding link not working

我正在尝试创建一个包含图像的 PDF 并调整 PDF 的大小并向其添加 link。我这样做是为了将 link 嵌入到我的图像中以用于多个项目。我正在使用 PDFsharp。我让它在图像上使用 link 时工作正常,但是当我调整 PDF 页面大小时,我的 link 将不再工作。

private static void createPDF()
{
    string image = "C:\download.png";
    string filename = "C:\Test.pdf";
    PdfDocument doc = new PdfDocument();
    PdfPage page = doc.AddPage();
    XGraphics gfx = XGraphics.FromPdfPage(page);
    AddImage(gfx, page, image, 0, 0);
    doc.Save(filename);
}
private static void AddImage(XGraphics gfx, PdfPage page, string imagePath, int xPosition, int yPosition)
{
    if (!File.Exists(imagePath))
    {
        throw new FileNotFoundException(String.Format("Could not find image {0}.", imagePath));
    }

    XImage xImage = XImage.FromFile(imagePath);
    page.Width = xImage.PixelWidth;
    page.Height = xImage.PixelHeight;
    gfx.DrawImage(xImage, xPosition, yPosition, xImage.PixelWidth, xImage.PixelHeight);
    XRect rec = gfx.Transformer.WorldToDefaultPage(new XRect(new XPoint(xPosition, yPosition), new XSize(page.Width, page.Height)));
    PdfRectangle rect = new PdfRectangle(rec);
    page.AddWebLink(rect, "http://www.google.com");
}

我在发布问题后立即找到了问题的解决方案。

private static void AddImage(XGraphics gfx, PdfPage page, string imagePath, int xPosition, int yPosition)
{
    if (!File.Exists(imagePath))
    {
        throw new FileNotFoundException(String.Format("Could not find image {0}.", imagePath));
    }

    XRect rec = gfx.Transformer.WorldToDefaultPage(new XRect(new XPoint(xPosition, yPosition), new XSize(page.Width, page.Height)));
    PdfRectangle rect = new PdfRectangle(rec);
    page.AddWebLink(rect, "http://www.google.com");
    XImage xImage = XImage.FromFile(imagePath);
    page.Width = xImage.PixelWidth;
    page.Height = xImage.PixelHeight;
    gfx.DrawImage(xImage, xPosition, yPosition, xImage.PixelWidth, xImage.PixelHeight);
}

我只是重新整理了几行代码。

正确答案是:在获取XGraphics对象前必须先设置页面的Width和Height。

所以重新安排几行代码实际上就可以了。