Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page truncate in right side for landscape orientation with trimmargins using PdfSharp

I am talking about PdfSharp. Portrait orientation works well with margin or without margin. But In case of landscape orientation, page truncate in right side once I set any margin using TrimMargins. I have tried same thing on sample code of pdfSharp and having same problem!!

Look pdf rendered well for following code

page = document.AddPage();
page.Size = PdfSharp.PageSize.A4;
page.Orientation = PageOrientation.Landscape;
gfx = XGraphics.FromPdfPage(page);
gfx.DrawString("A4 (landscape)", font,XBrushes.DarkRed, new XRect(0, 0, page.Width, page.Height),XStringFormats.Center);

But for following code pdf is not rendered well, truncate in right side

page = document.AddPage();
page.TrimMargins.Top = 5;
page.TrimMargins.Right = 5;
page.TrimMargins.Bottom = 5;
page.TrimMargins.Left = 5;
page.Size = PdfSharp.PageSize.A4;
page.Orientation = PageOrientation.Landscape;
gfx = XGraphics.FromPdfPage(page);
gfx.DrawString("A4 (landscape)", font,XBrushes.DarkRed, new XRect(0, 0, page.Width, page.Height),XStringFormats.Center);

Have any idea? Thanks

like image 580
Shahdat Avatar asked Oct 25 '25 03:10

Shahdat


1 Answers

Could be a bug in PDFsharp.

As a workaround, do not set the orientation to Landscape, instead swap width and height when creating the page.

page = document.AddPage();
//page.Size = PdfSharp.PageSize.A4;
XSize size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);
page.MediaBox = new PdfRectangle(new XPoint(0, 0), new XPoint(size.Height, size.Width)); // Magic: swap width and height
//page.Orientation = PageOrientation.Landscape;

The default unit for margins is Points. To get e.g. millimetres instead, you can write:

page.TrimMargins.Top = XUnit.FromMillimeter(5);
page.TrimMargins.Right = XUnit.FromMillimeter(5);
page.TrimMargins.Bottom = XUnit.FromMillimeter(5);
page.TrimMargins.Left = XUnit.FromMillimeter(5);
like image 199
I liked the old Stack Overflow Avatar answered Oct 27 '25 17:10

I liked the old Stack Overflow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!