Skip to content

Commit

Permalink
Fixed incorrect viewbox when MediaBox was smaller than CropBox (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmester committed Mar 10, 2024
1 parent 967b2b0 commit 4abe357
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
33 changes: 27 additions & 6 deletions src/PdfToSvg/Drawing/SvgRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,7 @@ private SvgRenderer(PdfDictionary pageDict, SvgConversionOptions? options, Docum

resources = new ResourceCache(pageDict.GetDictionaryOrEmpty(Names.Resources));

if (!pageDict.TryGetRectangle(Names.CropBox, out cropBox) &&
!pageDict.TryGetRectangle(Names.MediaBox, out cropBox))
{
// Default to A4
cropBox = RectangleUtils.GetA4();
}
cropBox = GetCropBox(pageDict);

var pageWidth = cropBox.Width;
var pageHeight = cropBox.Height;
Expand Down Expand Up @@ -173,6 +168,32 @@ private SvgRenderer(PdfDictionary pageDict, SvgConversionOptions? options, Docum
originalTransform = graphicsState.Transform;
}

private static Rectangle GetCropBox(PdfDictionary pageDict)
{
var hasCropBox = pageDict.TryGetRectangle(Names.CropBox, out var cropBox);
var hasMediaBox = pageDict.TryGetRectangle(Names.MediaBox, out var mediaBox);

if (hasCropBox && hasMediaBox)
{
// The spec says the CropBox should be considered to be the intersection
// if the CropBox extends outside the MediaBox.
return Rectangle.Intersection(cropBox, mediaBox);
}

if (hasCropBox)
{
return cropBox;
}

if (hasMediaBox)
{
return mediaBox;
}

// Default
return RectangleUtils.GetA4();
}

private static Matrix MoveOriginToTopLeft(Rectangle bbox)
{
var matrix = Matrix.Scale(1, -1);
Expand Down
6 changes: 6 additions & 0 deletions tests/TestFiles/Own/expected/page-boxes-small-mediabox.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.

0 comments on commit 4abe357

Please sign in to comment.