Hi I'm wondering how I can scale down / resize a pdf content page per page and my pages could have different size and orientation. My expected result would be a A4 page with the content that best fit to it.
Based on these topics:
- How to resize content of PDF without affecting page size?
- Using GhostScript to get page size
- How to make per-page changes to a pdf document using Ghostscript?
I written a simple code but since I'm really begin with this it is probably not the way to do it.
const script = `
FileName (r) file % open file given by -sFileName
runpdfbegin % open file as pdf
1 1 pdfpagecount { % for each page index
pdfgetpage % get pdf page properties (pushes a dict)
/MediaBox get % get MediaBox value from dict (pushes an array of numbers [ offsetX offsetY width height ])
% Define the new expected height & width
/nheight ${newHeight} def
/nwidth ${newWidth} def
% Destruct the array to the stack
aload pop
/pheight exch def
/pwidth exch def
pop pop
% Compute scales
nheight pheight div % compute scale ratio of height
nwidth pwidth div % compute scale ratio of width
% Now we have the two scale ratio
1 index 1 index lt
{ % if scaleY < scaleX
pop
}
{
exch
pop
}
ifelse
/pscale exch def
% At this stage I have the min scale
% Compute translateX
pwidth pscale pwidth % (WIDTH - (scale * WIDTH)) / 2
mul sub 2 div round
/ptranslateX exch def
% Compute translateY
pheight pscale pheight % (HEIGHT - (scale * HEIGHT)) / 2
mul sub 2 div round
/ptranslateY exch def
% Now build the scale and translate operation
<</BeginPage{pscale pscale scale ptranslateX ptranslateY translate}>> setpagedevice
} for`
// Resize the page
await spawnProcess('gs', [
'-sDEVICE=pdfwrite',
'-dPDFSETTINGS=/ebook',
'-dCompatibilityLevel=1.5',
'-dSubsetFonts=true',
'-dEmbedAllFonts=true',
'-dFIXEDMEDIA',
'-dSAFER',
'-dNOPAUSE',
'-dBATCH',
'-dUNROLLFORMS',
'-dAutoRotatePages=/PageByPage',
'-dFitPage',
`-sOutputFile=${filename}-resized.pdf`,
`-dDEVICEWIDTHPOINTS=595`,
`-dDEVICEHEIGHTPOINTS=842`,
// '-c', `<</BeginPage{${scale} ${scale} scale ${translateX} ${translateY} translate}>> setpagedevice`,
'-c', script,
'-sFileName', filename
])
Note: Using ghostscript -dFitPage
option works on some pdf but not all of them in contrary to -c "<</BeginPage{${scale} ${scale} scale ${translateX} ${translateY} translate}>> setpagedevice"
that works on all the pdfs I tested but does not fit page per page. That's why I'm trying to do a custom script.
It would be great if you could help me to be on the right way