Overlay a PS file on top of PDF file - pdf

I found similar question that was answered Overlay two postscript files (command line approach)?, However, that solution does not work for me and my requirements are bit different (one of my files is multi-page file)
I have a PDF File (DrawingSheet.pdf) that is generated outside my control. I have a PostScript file (Table.ps) that I generate by converting XML file using XSLFO and Apache FOP. Table.ps contains one table.
The DrawingSheet.pdf has multiple pages. Table.ps has only one page. Both DrawingSheet.pdf and Table.ps has same paper size - A size, Landscape. I want to place that table from the Table.ps on top of the last page of the DrawingSheet.pdf. I don't want to "append" table page as additional page at the end of the DrawingSheet.pdf. I am using command-line GhostScript (v9.27).
Per the suggestion from that post, I wrote following Overlay.ps file:
/origshowpage /showpage load def
/showpage {} def
gsave
(DrawingSheet.pdf) run
grestore
(Table.ps) run
origshowpage
That does not work. What I get is the table page "appended" to the DrawingSheet.pdf rather than overlaying on top of the last page.
What am I doing wrong? How can I achieve what I want?
Edited-1:
If it helps to have same number of pages in both files to simplify logic, then I can generate Table.ps to have same number of pages as DrawingSheet.pdf file and have the table appear only on the last page of the Table.ps.
Edited-2:
Alternatively, I tried following approach (similar to adding image watermark to PDF file). Net result of this is that I as many blank pages as number of pages in DrawingSheet.pdf. Interestingly though, when I load that blank resulting PDF, I can see that the Acrobat Reader flashes the table across the screen, but when the entire file is loaded all I see in the end are blank pages.
Any help in solving this much appreciated.
<<
/EndPage
{
2 eq
{
pop false
}
{
gsave
1 dict begin
/showpage {} def
(Table.ps) run
end
grestore
pop true
} ifelse
} bind
>> setpagedevice
Edited-2 - Additional Notes: If I comment out gsave and grestore from above code, then I don't get blank pages but instead every page is now "replaced" (no overlay) with the table from Table.ps.
Edited-3 - Partial Success:
After coming across this post: Edit (every page of a) Postscript file manually, I tried that approach. I converted the DrawingSheet.pdf to DrawingSheet.ps, identified the last %%EndPageSetup line, and inserted following code after that line:
% BUNCH OF LINES NOT SHOWN %
%%BeginPageSetup
4 0 obj
<</Type/Page/MediaBox [0 0 792 612]
/Parent 3 0 R
/Resources<</ProcSet[/PDF]
/Font 10 0 R
>>
/Contents 5 0 R
/CropBox
[0 0 792.0 612.0]
/BleedBox
[0 0 792.0 612.0]
/TrimBox
[0 0 792.0 612.0]
>>
endobj
%%EndPageSetup
%gsave % <== My Edits
1 dict begin % <== My Edits
/showpage {} def % <== My Edits
(Table.ps) run % <== My Edits
end % <== My Edits
%grestore % <== My Edits
5 0 obj
<</Length 30050>>stream
% BUNCH OF LINES NOT SHOWN %
With this edits (gsave and grestore commented out - if I uncomment them then this does not work), I get my table super imposed on the last page. Table appears fine, however the original last page from the pdf appears as flipped over the center on X axis after super imposing. The screenshot of the page is:
Text that you can read is from the Table.ps, while the text that is flipped is the original text from the last page of the DrawingSheet.pdf (of course that page in original pdf is not flipped).
Not sure what I am doing wrong to get that flipped image?
Edited-4:
Added additional notes to "Edited-2"

I tried your endpage and finally got this approach to work. The EndPage puts the reason code 0 or 1 and the page count on the stack (unreliably for some pdfs) so an alternative is the /PageCount variable and I show both. These count the number of pages and are incremented at the end of the page.
You need to know the number of pages to put the overlay on the page before the page is finished. The "finalpage" variable can also be defined on the ghostscript command line instead of in the file. Run ghostscript with both your endpage.ps and DrawingSheet.ps files as arguments. More work would be needed to adapt this to a DrawingSheet.pdf except that should be possible.
See if this works after changing the finalpage number. The table.ps should be placed on top of the original last page before the showpage is executed.
%!
/finalpage 9 def
<<
/EndPage {
2 ne {
1 add finalpage eq {(found last page\n)print (Table.ps)run} if
currentpagedevice /PageCount get ==
true
} if
}
>> setpagedevice
EDIT: The Postscript Language Reference Manual 3 page 176 says this:
The PostScript interpreter maintains an implicit current page that accumulates the marks made by the painting operators. When a program begins, the current page is completely blank. As each painting operator executes, it places marks on the current page. Each new mark completely obscures any marks it may overlay. This method is known as a painting model: no matter what color a mark has—white, black, gray, or color—it is put onto the current page as if it were applied with opaque paint. Once the page has been completely composed, invoking the showpage operator renders the accumulated marks on the output media and then clears the page to white again.

After many trials and errors and of course suggestions/comments from fellow SO users like #beginner6789 and #luserdroog (my thanks to both of them), I finally got something that works for my case. I am going to summarize my experiments and findings for benefits of others.
For this discussion, let's say you want to superimpose a page from Overlay.* (.ps or .pdf) on top of one particular page from Base.* (.ps or .pdf). There does not appear to be one solution fit all scenarios. It depends on:
If the you have Overlay.ps or Overlay.pdf. Although converting them is quite easy.
If the you have Base.ps or Base.pdf. Although converting them is quite easy.
If the Overlay.ps or Base.ps is auto-generated from corresponding pdf file or if they are handwritten. I found that the handwritten PostScript files are much cleaner, precise, and optimized compared to auto-generated PostScript files.
Logic becomes more complex depending upon which page/s of Overlay file you want super imposed on top of which page/s of Base file. You may have to do some extra work to identify those pages.
Following are 3 solutions that I tried. To summarize: Solution-3 worked for me as described by the last row of the corresponding results table.
Solution-1:
Create following Merge.ps and run it through your GhostScript to generate PDF output:
1 dict begin
/showpage {} def
(Base.ps) run % or Base.pdf
(Overlay.ps) run % or Overlay.pdf
end
showpage
Results:
Base File
Overlay File
Results/Notes
Base.pdf
Overlay.ps (Handwritten)
Overlay file is appended at the end of the Base file
Base.pdf
Overlay.ps (Converted from PDF)
Overlay file is appended at the end of the Base file
Base.pdf
Overlay.pdf
Overlay file and a blank page is appended at the end of the Base file
Base.ps (Converted from PDF)
Overlay.ps (Handwritten)
Single page PDF with all pages from Base file and Overlay file are superimposed on top of each other
Base.ps (Converted from PDF)
Overlay.ps (Converted from PDF)
Single page PDF with page from Overlay file only
Base.ps (Converted from PDF)
Overlay.pdf
Same as Overlay file with blank page appended at the end
Does not appear to be a suitable option if Base file is multi-page file.
Solution-2:
Create following Merge.ps and run it through your GhostScript along with Base file to generate PDF output:
<<
/EndPage
{
2 eq
{
pop false
}
{
1 dict begin
/showpage {} def
(Overlay.ps) run % or Overlay.pdf
end
pop true
} ifelse
} bind
>> setpagedevice
Additional logic is required if you want Overlay on only certain pages of the Base file.
Results:
Base File
Overlay File
Results/Notes
Base.pdf
Overlay.ps (Handwritten)
Overlay file is superimposed on top of every page of the Base file
Base.pdf
Overlay.ps (Converted from PDF)
Each page from Base file is replaced by the page from Overlay file
Base.pdf
Overlay.pdf
GhostScript crash after stack-overflow (no pun intended)
Base.ps (Converted from PDF)
Overlay.ps (Handwritten)
Overlay file is superimposed on top of every page of the Base file
Base.ps (Converted from PDF)
Overlay.ps (Converted from PDF)
Each page from Base file is replaced by the page from Overlay file
Base.ps (Converted from PDF)
Overlay.pdf
GhostScript crash
Solution-3:
Edit the Base.ps file that was converted from Base.pdf. Find the entry %%EndPageSetup corresponding to the page/s that you want overlay, and insert following code after that. Run it through your GhostScript to generate PDF output. In the example below I am editing it for the third page:
% BUNCH OF CODE NOT SHOWN HERE %
%%Page: 3 3
%%PageBoundingBox: 0 0 792 612
%%BeginPageSetup
8 0 obj
<</Type/Page/MediaBox [0 0 792 612]
/Parent 3 0 R
/Resources<</ProcSet[/PDF]
>>
/Contents 9 0 R
/CropBox
[0 0 792.0 612.0]
>>
endobj
%%EndPageSetup
1 dict begin % <== My Edits
/showpage {} def % <== My Edits
(Overlay.ps) run % <== My Edits
% [1 0 0 -1 0 612] concat % <== My Edits. See Notes below.
end % <== My Edits
9 0 obj
% BUNCH OF CODE NOT SHOWN HERE %
Results:
Base File
Overlay File
Results/Notes
Base.ps (Converted from PDF & Edited)
Overlay.ps (Handwritten)
Overlay page is superimposed on top of the third page of the Base file
Base.ps (Converted from PDF & Edited)
Overlay.ps (Converted from PDF)
Overlay page is superimposed on top of the third page of the Base file, but the third page of the base file appears as a X-axis mirror of the original third page
Base.ps (Converted from PDF & Edited)
Overlay.pdf
Four page output of the Base file with Overlay page inserted as the third page.
Base.ps (Converted from PDF & Edited)
Overlay.ps (Converted from PDF with the transformation matrix concatenation uncommented from code above)
Overlay page is superimposed on top of the third page of the Base file as I wanted. This scenario works for me
In my case:
I had no control over how the Base.pdf file was generated, but I could convert it to Base.ps using GhostScript.
I had partial control over Overlay file generation. I had XML data, which I converted to table format using XSLFO, and then converted to PDF and PostScript file using Apache FOP.
I really had no option of manually writing Base.ps or Overlay.ps.
Considering, results of all these trials and errors, at this time the Solution-3 (with transformation matrix concatenated after the run command, the last row from that results table) is working for me. I don't particularly like this option, because it involves editing the auto-generated PostScript file.
NOTE: For all those cases where I saw that the page from Base file is being replaced by Overlay page, I think the original page from the Base file is being printed outside the output page size hence it is clipped and does not show and appears as being replaced. Maybe proper manipulation of the transformation matrix would fix those cases. I am yet to experiment with that scenario but don't know how to verify.

Related

Crop PDF Content

I have a pdf that I would like to impose. It has 8.5x11" pages, media box, and crop box. I want the pdf to have 17x11" pages, by merging adjacent pages. Unfortunately, most pages have content either completely outside or straddling the crop box. Because each page can only have a single stream and crop box, when imposed, the overlapping content becomes visible. This is bad.
I don't want to rasterize my pdf because that would fix the DPI ahead-of-time. So I won't consider exporting pages as images, appending the images (imagemagick), then embedding these paired images into a new pdf.
I've also had problems imposing in postscript - issues with transparency, font rasterization, and other visual glitches during the pdf->ps->pdf conversions.
The answer should be scriptable.
So far I've tried:
podofo imposition scripts (lua)
PyPDF2 (python)
ghostscript
latex
The question "Ghostscript removes content outside the crop box?" suggests that ghostscript's pdfwrite module, when generating an output pdf file, will rasterize and crop content according to the crop box. So I'd only have to pipe my pdf through ghostscript's pdfwrite module. Unfortunately, this doesn't work.
I was about to give up when I tried printing the pdf to another pdf through evince. It works perfectly - text & vector elements within the crop box are not rasterized, and elements outside the crop box are removed (I haven't tested straddling elements yet). The quality is high - resolution (page size) and appearance are identical. In fact, everything seems to be the same except for the metadata.
So:
the question is possible
the answer already exists
How can I access it?
I think this functionality might be provided by cup's pdftopdf binary. I don't have any problems calling an external binary.... but can't figure out how to use pdftopdf.
Edit: Link to test pdf. It contains raster, vector, and text items - some partially occluded by partially transparent items - that span as well as abut adjacent pages. Once again, printing this PDF through cups appears to crop all content outside the crop box. However, opening the filtered pdf in inkscape shows that the off-page items are individually masked, not cropped - except text, which is trimmed.
The trick is to use Form XObjects to impose multiple pages within a single page. Form XObjects can reference entire PDF pages, and maintain independent clips. PyPDF2 doesn't support Form XObjects, so merging unifies the stream of all input pages such that they share the clip/media box of the output page. I've been successful in using both pdflatex and pdfrw (python) - test programs are inlined below. Since Form XObjects are derived from a similar postscript level 2 feature, as suggested by KenS it should be possible to achieve the same goal in ghostscript using "page clips". In fact he shared a ghostscript 2x1 imposition script in another answer, but it appears horrendously complicated. Combined with the font rasterization issues of poppler's pdftops (even with compatibility level > 1.4), I've abandoned the ghostscript approach.
Latex script derived from How to stitch two PDF pages together as one big page?. Requires pdflatex:
\documentclass{article}
\usepackage{pdfpages}
\usepackage[paperwidth=8.5in, paperheight=11in]{geometry}
\usepackage[multidot]{grffile}
\pagestyle{plain}
\begin{document}
\setlength\voffset{+0.0in}
\setlength\hoffset{+0.0in}
\includepdf[ noautoscale=true
, frame=false
, pages={1}
]
{<file.pdf>}
\eject \paperwidth=17in \pdfpagewidth=17in \paperheight=11in \pdfpageheight=11in
\includepdf[ nup=2x1
, noautoscale=true
, frame=false
, pages={2-,}
]
{<file.pdf>}
\end{document}
pdfrw (python script) derived from pdfrw:examples:booklet. Requires pdfrw >= 0.2:
#!/usr/bin/env python3
# Copyright:
# Yclept Nemo
# 2016
# License:
# GPLv3
import itertools
import argparse
import pdfrw
# from itertool recipes in the python documentation
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
def pagemerge(page, *pages):
merged = pdfrw.PageMerge() + page
for page in reversed(list(itertools.takewhile(lambda i: i is not None, reversed(pages)))):
merged = merged + page
merged[-1].x = merged[-2].x + merged[-2].w
return merged.render()
parser = argparse.ArgumentParser(description='Impose PDF files using Form XOBjects')
parser.add_argument\
( "source"
, help="PDF, source path"
, type=pdfrw.PdfReader
)
parser.add_argument\
( "-s", "--spacer"
, help="PDF, spacer path"
, type=lambda fp: next(iter(pdfrw.PdfReader(fp).pages), None)
)
parser.add_argument\
( "target"
, help="PDF, target path"
)
args = parser.parse_args()
pages = args.source.pages[:1]
for pair in grouper(args.source.pages[1:], 2):
assert pair[0] is not None
pages.append(pagemerge(pair[0], args.spacer, pair[1]))
# include metadata in target
target = pdfrw.PdfWriter()
target.addpages(pages)
target.trailer.Info = args.source.Info
target.write(args.target)
Some idiosyncrasies as of pdfrw 0.2:
Note that the operations +=, append and extend are not defined for pdfrw.PageMerge, even though it behaves like a list. Furthermore + acts like += in that it modifies the left-hand-side object.
Ghostscript and the pdfwrite device do not, in general, rasterise the content of input PDF files (the caveat is for cases involving transparent input and the output being < PDF 1.4).
Object which are entirely clipped out are not preserved into the output.
So the short answer is that this should be entirely feasible using Ghostscript and the pdfwrite device, with the advantage that its possible to impose the pages as well in a single operation. I do have an open bug report about clipping in a similar situation (reverse imposition) but have not yet had time to address it.
Note that Ghostscript normally uses the MediaBox for the clip region, if you want to use the CropBox then you need to add -dUseCropBox to the command line.

can I create a PDF from ImageMagick which will always open at zoom 100%? [duplicate]

I am running into an issue with PNG to PDF conversion.
Actually I have big PNG files not in size but in contents.
In PDF conversion it creates a big PDF files. I don't have any issue with its quality, but whenever I try to open this PDF in PDF viewer, it opens in "Fit to Page" mode.
So, I can't see the created PDF in the initial view, but I need to zoom it up to 100%.
My question is: can I create a PDF which will always open at zoom 100% ?
You can possibly achieve what you want with the help of Ghostscript.
Ghostscript supports to insert PostScript snippets into its command line parameters via -c "...[PostScript code here]...".
PostScript has a special operator called pdfmark. This operator is not understood by most PostScript interpreters, but is understood by Acrobat Distiller and (for most of its parameters) also by Ghostscript when generating PDFs.
So you could try to insert
-c "[ /PageMode /UseNone /Page 1 /View [/XYZ null null 1] \
/PageLayout /SinglePage /DOCVIEW pdfmark"
into a PDF->PDF conversion Ghostscript command line.
Please take note about various basic things concerning this snippet:
The contents of the command line snippet appears to be 'unbalanced' regarding the [ and ] operators/keywords. But it is not! The initial [ is balanced by the final pdfmark keyword. (Don't ask -- I did not define this syntax...)
The 'inner' [ ... ] brackets delimit an array representing the page /View settings you desire.
Not all PDF viewers do respect the view settings embedded in the PDF file (Acrobat software does!).
Most PDF viewers allow users to override the view settings embedded in PDF files (Acrobat software also does this). That is, you can tell your viewer to never respect any settings from the PDF files it opens, but f.e. to always open it with "fit to width".
Some specific things about this snippet:
The page mode /UseNone means: the document displays without bookmarks or thumbnails. It could be replaced by
/UseOutlines (to display bookmarks also, not just the pages)
/UseThumbs (to display thumbnail images of the pages, not just the pages
/FullScreen (to open document in full screen mode)
The array for the view mode constructed as [/XYZ <left> <top> <zoom>] means: The zoom factor is 1 (=100%), the left distance from the page origin is the special 'null' value, which means to keep the previously user-set value; the top distance from the page origin is also 'null'. This array could be replaced by
/Fit (to adapt the page to the current window size)
/FitB (to adapt the visible page content to the current window size)
/FitH <top>' (to adapt the page width to the current window width);` indicates the required distance from page origin to upper edge of window.
...plus several others I cannot remember right now.
So to change the settings of an existing PDF file, you could do the following:
gs \
-o out.pdf \
-sDEVICE=pdfwrite \
-c "[ /PageMode /UseNone /Page 1 /View [ /XYZ null null 1 ] " \
-c " /PageLayout /SinglePage /DOCVIEW pdfmark" \
-f in.pdf
To check if the Ghostscript command worked, open the PDF in a text editor which is capable of handling binary files. Search for the /View or the /PageMode keywords and check if they are there, inserted as values into the PDF root object.
If it worked, check if your PDF viewer honors the settings. If it doesn't honor them, see if there is an overriding setting within the viewers preference settings.
I did a quick test run on a sample PDF of mine. Here is how the PDF root object's dictionary looks now, checked with the help of pdf-parser.py:
pdf-parser-beta.py -s Catalog a.pdf
obj 1 0
Type: /Catalog
Referencing: 3 0 R, 9 0 R
<<
/Type /Catalog
/Pages 3 0 R
/PageMode /UseNone
/Page 1
/View [/XYZ null null 1]
/PageLayout /SinglePage
/Metadata 9 0 R
>>
To learn more about the pdfmark operator, google for 'pdfmark reference filetype:pdf'. You should be able to find it on the Adobe website and elsewhere:
https://www.google.de/search?q=pdfmark%20reference%20filetype%3Apdf&oq=pdfmark%20reference%20filetype%3Apdf
In order to let ImageMagick create a PDF as you want it, you may be able to hack the file defining your delegate settings. For more help about this topic see for example here:
http://www.imagemagick.org/Usage/files/#delegates
PDF specification supports this functionality in this way: create a GoTo action that goes to first page and sets the zoom level to 100% and then set the action as the document open action.
How exactly you implement it in real life depends very much on the tool you use to create the PDF file. I do not know if ImageMagick can create such actions.

How to annotate PS or PDF from (Linux) command line without losing quality?

Is there any command line tool for Linux that will allow me to annotate a PS or PDF file with text or a particular font, color, and size with no loss of quality? I have tried ImageMagick's convert, and the resulting PDF is of pretty poor quality.
I have a template originally authored in Adobe Illustrator, and I would like to generate PDFs from it with names in certain places. I have a huge list of names, so I would like to do this in a batch (not interactively).
If anyone has any ideas I'd appreciate hearing them.
Thanks,
Carl
Another way to accomplish this would be to hack the postscript file itself. It used to be that AI files were postscript files, and you could modify them directly; I don't know if that's true anymore. So you may have to export it.
For simplicity, I assume there's a single page. Therefore, at the very end there will be a single call to showpage (perhaps through another name). Any drawing commands performed before showpage will show up on the page.
You may need to reinitialize the graphics state (initgraphics), as the rest of the document may have left it all funny, expecting showpage to clean up before anyone notices.
To place text, you'll need to set a new font (the old one was invalidated by initgraphics) measure the location in points (72 points/inch, 28.3465 points/cm).
/Palatino-Roman 17 selectfont %so much prettier than Times
x y moveto
(new text) show
To do the merging, you can use perl: emit the beginning of the document as a HERE-document, construct some text-writing lines by program, emit the tail of the document. Here's an example of generating postscript with PERL
Or you can take data from the command-line (with ghostscript) by using the -- option ($gs -q -- program.ps arg1 arg2 ... argn). These arguments are accessible to the program through an array named /ARGUMENTS.
So, say you have a nice graphic of a scary clown holding a blank sign about 1 inch wide, 3 inches tall, top left corner at 4 inches from the left, 4 inches from the bottom. You can insert this code into the ps program, just before showpage.
initgraphics
/Palatino-Roman 12 selectfont
4 72 mul 4 72 mul moveto
ARGUMENTS {
gsave show grestore 0 -14 rmoveto
} forall
Now you can make him say funny things ($gs -- clown.ps "On a dark," "and stormy night...").
I think it's better to create PDF form and fill it with pdftk fill_form in batch:
$ pdftk form.pdf fill_form data.fdf output out.pdf flatten
Form data should be in Forms Data Format (it's just XML file with field names and values specified).
Note the flatten command. It is required to convert filled form to plain document.
Another way is to create set of PDF documents "with names in certain places" and transparent background, and pdftk stamp each of them over the template:
$ pdftk template.pdf stamp words.pdf output out.pdf

Rendering the whole media box of a pdf page into a png file using ghostscript

I'm trying to render Pdfs pages into png files using Ghostscript v9.02. For that purpose I'm using the following command line:
gswin32c.exe -sDEVICE=png16m -o outputFile%d.png mypdf.pdf
This is working fine when the pdf crop box is the same as the media box, but if the crop box is smaller than the media box, only the media box is displayed and the border of the pdf page is lost.
I know usually pdf viewers only display the crop box but I need to be able to see the whole media page in my png file.
Ghostscript documentation says that per default the media box of a document is rendered, but this does not work in my case.
As anyone an idea how I could achieve rendering the whole media box using ghostscript?Could it be that for png file device, only the crop box is rendered? Am I maybe forgetting a specific command?
For example, this pdf contains some registration marks outside of the crop box, which are not present in the output png file. Some more information about this pdf:
media box:
width: 667
height: 908 pts
crop box:
width: 640
height: 851
OK, now that revers has re-stated his problem into that he is looking for "generic code", let me try again.
The problem with a "generic code" is that there are many "legal" formal representations of "CropBox" statements which could appear in a PDF. All of the following are possible and correct and set the same values for the page's CropBox:
/CropBox[10 20 500 700]
/CropBox[ 10 20 500 700 ]
/CropBox[10 20 500 700 ]
/CropBox [10 20 500 700]
/CropBox [ 10 20 500 700 ]
/CropBox [ 10.00 20.0000 500.0 700 ]
/CropBox [
10
20
500
700
]
The same is true for ArtBox, TrimBox, BleedBox, CropBox and MediaBox. Therefor you need to "normalize" the *Box representation inside the PDF source code if you want to edit it.
First Step: "Normalize" the PDF source code
Here is how you do that:
Download qpdf for your OS platform.
Run this command on your input PDF:
qpdf --qdf input.pdf output.pdf
The output.pdf now will have a kind of normalized structure (similar to the last example given above), and it will be easier to edit, even with a stream editor like sed.
Second Step: Remove all superfluous *Box statements
Next, you need to know that the only essential *Box is MediaBox. This one MUST be present, the others are optional (in a certain prioritized way). If the others are missing, they default to the same values as MediaBox. Therefor, in order to achieve your goal, we can simply delete all code that is related to them. We'll do it with the help of sed.
That tool is normally installed on all Linux systems -- on Windows download and install it from gnuwin32.sf.net. (Don't forget to install the named "dependencies" should you decide to use the .zip file instead of the Setup .exe).
Now run this command:
sed.exe -i.bak -e "/CropBox/,/]/s#.# #g" output.pdf
Here is what this command is supposed to do:
-i.bak tells sed to edit the original file inline, but to also create a backup file with a.bak suffix (in case something goes wrong).
/CropBox/ states the first address line to be processed by sed.
/]/ states the last address line to be processed by sed.
s tells sed to do substitutions for all lines from first to last addressed line.
#.# #g tells sed which kind of substitution to do: replace each arbitrary character ('.') in the address space by blanks (''), globally ('g').
We substitute all characters by blanks (instead of by 'nothing', i.e. deleting them) because otherwise we'd get complaints about "PDF file corruption", since the object reference counting and the stream lengths would have changed.
Third step: run your Ghostscript command
You know that already well enough:
gswin32c.exe -sDEVICE=png16m -o outputImage_%03d.png output.pdf
All the three steps from above can easily be scripted, which I'll leave to you for your own pleasure.
First, let's get rid of a misunderstanding. You wrote:
"This is working fine when the pdf crop box is the same as the media box, but if the crop box is smaller than the media box, only the media box is displayed and the border of the pdf page is lost."
That's not correct. If the CropBox is smaller than the MediaBox, then only the CropBox should be displayed (not the MediaBox). And that is exactly how it was designed to work. This is the whole idea behind the CropBox concept...
At the moment I cannot think of a solution that works automatically for each PDF and all possibly values that can be there (unless you want to use payware).
To manually process the PDF you linked to:
Open the PDF in a good text editor (one that doesn't mess with existing EOL conventions, and doesn't complain about binary parts in the file).
Search for all spots in the file that contain the /CropBox keyword.
Since you have only one page in the PDF, it should find only one spot.
This could read like /CropBox [12.3456 78.9012 345.67 890.123456].
Now edit this part, carefully avoiding to add to (or lose from) the number of already existing characters:
Set the value to your wanted one: /CropBox [0.00000 0.00000 667.00 908.000000]. (You can use spaces instead of my .0000.. parts, but if I do, the SO editor will eat them and you'll not see what I originally typed...)
Save the file under a new name.
A PDF viewer should now show the full MediaBox (as of your specification).
When you convert the new file with Ghostscript to PNG, the bigger page will be visible.

Is there an "Export to Pdf" plugin for Tiddlywiki?

Has anyone put together a plugin or tool for exporting a Tiddlywiki to pdf?
No, there isn't.
As a workaround, I write or find a decent printable stylesheet, then print to PDF.
Why not select the target tiddler to "Open in new window", and print it to PDF with any installed PDF printer?
To accomplish this I used a tool to convert HTML to PDF. These steps are a bit long but well worth it. Once you've got it working it is easily repeated.
In each tiddler that I want in my PDF, I mark with a specific tag; I used TableOfContents.
In each tiddler that is marked with this tag, I added an order field--to be used to define the order of tiddlers to appear in the PDF.
Ensure your HTML headers are properly defined for the document. I think tiddler titles use <h2>, so properly defining subheadings using <h3><h4> etc will ensure, if you want, a nice auto-generated Table of Contents in your PDF.
If you want each tiddler to start on a new page (in the PDF), we need to add this HTML to the end of each tiddler:
<div style = "display:block; clear:both; page-break-after:always;"></div>
With a completed TiddlyWiki document export the tiddlers to a single HTML file--this will be used to generate a PDF document. To export, go to the AdvancedSearch, select the Filter tab. In the search textbox enter your filter criteria--for me that was:
[tag[TableOfContents]sort[order]]
You'll see, immediately, on-screen a list of the tiddlers the system found based on that criteria. Then click on the Export icon and select Static HTML.
Optionally, but I think it's a great idea, manually create a cover page (in your favorite editor)--this will be a single HTML file to act as the cover page in the PDF document; call it cover.html. More on this later.
Download and install wkhtmltopdf (command-line tool to generate PDF from an HTML file).
https://wkhtmltopdf.org/downloads.html
Learn and get familiar with the wkhtmltopdf command line syntax. There are numerous features here so the command you end up with maybe lengthy. Use wkhtmltopdf /? to view general help, then wkhtmltopdf --extended-help to view details (well worth the read).
Generate a PDF document. At the command prompt navigate to the folder where your TiddlyWiki document is located. Here is a list of my favorite command-line switches. My app is installed in C:\Program Files..., so my command line starts with that...
"c:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"
Add this switch for a header on the left:
--header-left "My document title"
For a header on the right:
--header-right "v1.0.0.1"
Font size of header:
--header-font-size 8
Display a line below the header:
--header-line
Spacing between header and content in mm (default 0):
--header-spacing 5
A left-footer ([section] is replaced with the name of the current section:
--footer-left "[section]"
A centered footer:
--footer-center "Page [page] of [topage]"
Footer font size:
--footer-font-size 8
Footer spacing:
--footer-spacing 5
If you want titles to hyperlink (in the PDF) to go back to the TOC:
--enable-toc-back-links
Make sure no background images get printed:
--no-background
I added special styles in the TiddlyWiki document for print media--to hide tags and clean up the spacing. Then I used this switch to ensure print media is used:
--print-media-type
Being in North America I want letter-size pages; I think the default is A4:
-s Letter
IMPORTANT--give the tool access to local files, otherwise your images will be missing in the PDF:
--enable-local-file-access
Use this if you want to have a cover page (see step 6 above):
cover "cover.htm"
And use this if you want a TOC automatically generated. Without a cover page, the TOC will be your first page, so create a cover page:
toc
After the toc identify your exported tiddler HTML file as input to the tool:
tiddlers.html
And, the final argument on the command line is the output PDF file name:
MyDocument.pdf
Export the tid to html.
Then in the terminal, issue:
html2pdf $myTid.html $myTid.pdf
$myTid is only a var and can be any name
:)