【问题标题】:PDFsharp adding link not workingPDFsharp添加链接不起作用
【发布时间】:2023-03-17 14:22:01
【问题描述】:

我正在尝试创建一个包含图像的 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");
}

【问题讨论】:

    标签: c# image pdf hyperlink pdfsharp


    【解决方案1】:

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

    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.FromPdfPage(page);之前设置页面的宽度和高度,应该是正确的。
    【解决方案2】:

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

    因此,实际上只重新排列几行代码就可以解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      相关资源
      最近更新 更多