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

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.

Related

How to modify the display settings of a pdf file in double-page view?

I have converted a pdf-file using ghostscript to pdf/A-2 using
gs -dPDFA=2 -dPrinted=false -dBATCH -dNOPAUSE -sProcessColorModel=DeviceCMYK -sDEVICE=pdfwrite -sPDFACompatibilityPolicy=1 -sOutputFile=file_PDFA-2.pdf file.pdf
I have used ghostscript version 9.26 on Ubuntu 18.04.5 LTS.
I use Acrobat Reader to display the pdf-document in double page view. Before using ghostscript, the first page is correctly show to the right (see figure). The ghostscript command apparently modifies this, which makes the document harder to read.
Is there a way in ghostscript to modify this setting? Unfortunately, I couldn't find an option. Using other freely available tools to modify the settings after using ghostscript would also work.
Edit: link to the pdf-files before and after the conversion:
link to the pdf-files
Thank you.
So looking at the before PDF file I see, in the document Catalog (after decompressing the file):
28 0 obj
<<
/Type /Catalog
/Pages 12 0 R
/Names 27 0 R
/PageMode /UseOutlines
/PageLayout /TwoPageRight
/OpenAction 4 0 R
>>
endobj
And in the after file I see the Catalog only contains:
1 0 obj
<<
/Type /Catalog
/Pages 3 0 R
/Metadata 24 0 R
>>
endobj
So it seems likely that the '/PageLayout' key having the value '/TwoPagesRight' is what causes Acrobat to display the way it does. Noe the /PageMode /UseOutlines which appears to be pointless since the PDF file doesn't actually seem to contain any Outlines.
We can use a /PUT pdfmark to add entries to dictionaries, and that is supported by both the pdfwrite device and the interpreter.
[ {Catalog} << /PageLayout /TwoPageRight >> /PUT pdfmark
Should work, but unfortunately does not for me.
Disclaimer,
I support SumatraPDF and am taking the question at face value
"How to modify the display settings of a pdf file in double-page
view?"
plus the stated desire
"Using other freely available tools to modify the settings after using
ghostscript would also work."
So without rotation the pages can be displayed 4 different layouts in a viewer. here are the main 3
Facing Manga (RTL) Cover (Book)

Using Ghostscript to look only at specific area when using inkcov

I use Ghostscript to check if part of a pdf page is empty of content or not by cropping the area I'm interested in (using iTextSharp in vb.net) and then running:
gswin64c.exe -o - -sDEVICE=inkcov c:\cropped.pdf
This works well enough, but it would be much better if I could get Ghostscript to look at a specific rectangle area on the page (instead of the whole page), to remove the need for cropping first.
Is this possible?
You can use -dDEVICEWIDTHPOINTS and -dDEVICEHEIGHTPOINTS along with -dFIXEDMEDIA to specify a fixed media size. You want to set that to the 'window' size you want to use.
You then need to shift the PDF content so that the portion of the page you are interested in lies under the window. To do that you need to write some PostScript code.
You need to define a BeginPage procedure, that will be executed at the start of every page, in there you need to translate the page origin.
So lets take a specific example:
Say that you have an A4 page (612x792 points) and you want to limit the rendered content to a 1x2 inch rectangle at the top right. We start by defining the media size:
-dDEVICEWIDTHPOINTS=72 -dDEVICEHEIGHTPOINTS=144 -dFIXEDMEDIA
We then need to shift the origin (0,0) which is the bottom left corner in PostScript and PDF, so that only the top right section of the content lies on the page. That means we need to shift the content 540 points to the left, and 648 points down. So our BeginPage procedure is:
/BeginPage {-540 -648 translate}
and we install that in the current page device thus:
<<
/BeginPage {-540 -648 translate}
>> setpagedevice
In order to introduce arbitrary PostScript we use the -c command (and we need to tell GS when we're done, we usually use the -f switch for that but any switch would do)
So your original command line would then be:
gswin64c -dDEVICEWIDTHPOINTS=72 -dDEVICEHEIGHTPOINTS=144 -dFIXEDMEDIA -sDEVICE=inkcov -o - -c "<</BeginPage {-540 -648 translate}>> setpagedevice" -f original.pdf
Obviously the exact numbers here are going to be up to you to determine.

Export PDF page labels on command line

I'd like to export the page-labels stored in some PDF documents for easy parsing. I know I could dig into the PDF document after having it converted with qpdf, but this seems like overkill.
Is there no commandline tool that will simply print the page label for each page (or together with other meta-data)? I know that PDFSpy will export the label, but $300 isn't an option, preferably the solution should be free.
Short answer:
I am not aware of any (free) tool that can 'simply print' the page label for each page.
Also, you'll not be able to evade the expansion compressed objects and object streams, using a tool like qpdf or one with equivalent capabilities.
Long answer:
There's no such tool because these are the only a few things you can safely rely on when it comes to page labels. These are the following:
Each PDF document must contain a root object.
That root object must be of /Type /Catalog.
The document's trailer will show where to find the object using the key /Root followed by the indirect object number reference.
IF a PDF document uses non-standard page labels, then the document root object must have an entry named /PageLabels.
Here is where it stops to be relatively easy. Because the object the /PageLabels key refers to may be contained in a compressed object stream. This means that you'd have to expand that object stream.
If you really succeeded to get the description of the page labels as ASCII, you'll discover that it's not an easily parseable flat list (like a dictionary is): it is a number tree.
I'll not go into the details of these complexities, because it would take a very long article to describe all possible variations. You better read it up directly in the official ISO PDF-1.7 specification.
But instead I'll give you an example in ASCII PDF code:
213 0 obj
<< /Type /Catalog
/PageLabels
<<
/Nums
[
0 << % start labeling from page no. 1
/S /r % label with lowercase roman numbers
>>
7 << % start new labeling from page no. 8
/S /D % label with standard decimal numbers
>>
11 << % start labeling page no. 12
/S /D % label with decimal numbers...
/P (ABCD-) % ...but using label prefix 'ABCD-'...
/St 3 % ...followed by '3' as the start decimal.
>>
]
>>
%%...........................
%%...more root object keys...
%%...........................
>>
endobj
The above example will label the pages number 1, 2, 3, ... (last) like this:
i
ii
iii
iv
v
vi
1
2
3
4
ABCD-3
ABCD-4
ABCD-5
ABCD-6
...and so on until last page...
As you can see, the PDF method of labeling pages (mapping page numbers to page names) is completely non-intuitive. You can only understand it by studying the PDF specification.
I've written a small command-line utility based on Poppler that does just this task: https://github.com/HeimMatthias/pdfpagelabels
Disclaimer: I'm the OP and created the original post under a different account. I have been using the solution via pdftk (listed in a comment above) successfully for years in my implementation. However, last year it was time to reimplement our system from scratch and we've had numerous instances where the pdf-tk output could not be parsed by our implementation.
The new command-line tool follows the philosophy of doing just one thing, but doing it well, and simply prints the page labels of all or selected pages of a pdf-file. If anyone finds this useful, and stumbles upon it here, all the better for it.

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.