Discovered a problem with PDFSharp when drawing in different scales using scale transform.
In this example we draw two rectangles in different scales, generate a XPS from FixedDocumentSequence
and finally convert the XPS to PDF using PDFsharps XPS converter.
var visual = new DrawingVisual();
DrawingContext dc = visual.RenderOpen();
// Setup transformations.
dc.PushTransform(new TranslateTransform(0, 1122.0));
dc.PushTransform(new ScaleTransform(3.77857136726379, -3.77857136726379));
dc.PushTransform(new TranslateTransform(-1719.41186523438, -1410.32360839844));
dc.PushTransform(new ScaleTransform(0.0117647061124444, 0.0117647061124444));
// Draw red rectangle.
var redPen = new Pen(Brushes.Red, 1);
var rectGeo1 = new RectangleGeometry(new Rect(160000, 130000, 8000, 5000));
dc.DrawGeometry(Brushes.Transparent, redPen, rectGeo1);
// Pop two transformations.
dc.Pop();
dc.Pop();
// Draw blue rectangle.
var bluePen = new Pen(Brushes.Blue, 0.5);
var rectGeo2 = new RectangleGeometry(new Rect(12, 12, 150.9408, 107.088539));
dc.DrawGeometry(Brushes.Transparent, bluePen, rectGeo2);
dc.Close();
// Generate XPS from DocumentSequence.
var a3Size = new Size(1587, 1123);
var docSeq = CreateDocumentSequence(a3Size, visual);
string dirPath = @"C:\Temp\";
string xpsFilePath = dirPath + "test.xps";
string pdfFilePath = dirPath + "test.pdf";
WriteXpsFile(docSeq, xpsFilePath);
// Generate PDF from XPS (PdfSharp)
XpsConverter.Convert(xpsFilePath, pdfFilePath, 0);
Complete program can be found here and VS solution here.
The red rectangle is expected to be aligned against the upper right corner of the blue rectangle. That is what we get when looking at the generated XPS:
But in the generated PDF we get a gap between the two rectangles.
Close-up
The problem is most obvious when drawing a long way from origin, in this example the red rectangle is placed at 160000;130000 in a scale of 1:85. The gap becomes larger the longer from origin you draw, could it be a precision/rounding error?
I've tried to resolve this problem without success. Any help finding the cause would be greatly appreciated! Note, I'm not sure if the problem is with the PDFSharp rendering or the XPS conversion.
I'm using PDFSharp 1.31 (newer versions doesn't include the XPS support).
Complete Visual Studio solution with this example (including PDFSharp lib) is available here.
Found the cause, PDFSharp is rounding the transformation matrix values to 4 decimals when generating the PDF which is not enough in this case.
To increase precision I changed from 4 to 8 digit placeholders in PdfContentWriter
:
This is the difference in the generated PDF (verbose mode when running debug):
Which result in a correctly rendered PDF:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With