TH-Soft wrote:
AIUI you have to call "WorldToDefaultPage" only for the rectangle you pass into "AddEmbeddedDocumentLink", but not for the rectangles you use with the XGraphics object.
Yes indeed, but this is just a positioning issue.
The actual issue is that when I click on the clickable area, nothing happens. I think the /GoToE action is not properly built. Or I did not understand how to reference the attached file with 'fileName' in the line:
Code:
PdfLinkAnnotation annot = page.AddEmbeddedDocumentLink(new PdfRectangle(rectangleBottomBased), fileName);
Corrected code for the positioning:
Code:
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Drawing.Layout;
using PdfSharp.Fonts;
using PdfSharp.Pdf;
using PdfSharp.Pdf.Annotations;
using PdfSharp.Snippets.Font;
namespace PdfSharp6Attachments
{
class Program
{
static void Main(string[] args)
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PDFsharp";
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
if (Capabilities.Build.IsCoreBuild)
GlobalFontSettings.FontResolver = new FailsafeFontResolver();
// Create a font.
var font = new XFont("Arial", 20, XFontStyleEx.BoldItalic);
// Draw the text
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
#region attach files
AttachFile(document, @"C:\Users\userxxx\Downloads\avion2.jpg", gfx, font);
#endregion
// Save the document...
const string filename = "HelloWorld.pdf";
document.Save(filename);
// ...and start a viewer.
//Process.Start(filename);
}
static void AttachFile(PdfDocument pdfDocument, string path, XGraphics gfx, XFont font)
{
var page = pdfDocument.Pages[0];
string fileName = Path.GetFileName(path);
pdfDocument.AddEmbeddedFile(fileName, File.OpenRead(path));
// draw rectangle
var rectangleTopBased = new XRect(30, 60, 300, 300);
XTextFormatter txtFormat = new XTextFormatter(gfx);
gfx.DrawRectangle(XBrushes.White, rectangleTopBased);
txtFormat.DrawString("hello attachment!",
font,
new XSolidBrush(XColor.FromKnownColor(XKnownColor.Black)),
rectangleTopBased,
XStringFormats.TopLeft);
var rectangleBottomBased = gfx.Transformer.WorldToDefaultPage(new XRect(new XPoint(30, 60), new XSize(300, 300)));
PdfLinkAnnotation annot = page.AddEmbeddedDocumentLink(new PdfRectangle(rectangleBottomBased), fileName);
//page.AddWebLink(new PdfRectangle(annotationSystemRectangle), "https://www.developpez.com/");
}
}
}
Anybody having a working example of a link to an attached file (PdfSharp6)?