C# PDFsharp添加链接不工作

C# PDFsharp添加链接不工作,c#,image,pdf,hyperlink,pdfsharp,C#,Image,Pdf,Hyperlink,Pdfsharp,我正在尝试创建一个包含图像的PDF,调整PDF大小并添加链接。我这样做是为了我可以嵌入一个链接到我的形象,在多个项目中使用。我正在使用PDFsharp。我在图片上的链接可以正常工作,但是当我调整PDF页面的大小时,我的链接就不能工作了 private static void createPDF() { string image = "C:\\download.png"; string filename = "C:\\Test.pdf"; PdfDocument doc =

我正在尝试创建一个包含图像的PDF,调整PDF大小并添加链接。我这样做是为了我可以嵌入一个链接到我的形象,在多个项目中使用。我正在使用PDFsharp。我在图片上的链接可以正常工作,但是当我调整PDF页面的大小时,我的链接就不能工作了

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对象之前,必须设置页面的宽度和高度


因此,仅仅重新安排几行代码实际上就可以做到这一点。

这似乎可行,但恐怕并不总是可行的。在调用
XGraphics.FromPdfPage(第页)之前设置页面的宽度和高度并且事情应该是正确的。