K2pdfopt(1)
π k2pdfopt(1) β General Commands Manual π
okay bestie, grab a snack, this one is long but we're getting through it together. no cap. π
β¨ NAME β¨
k2pdfopt β PDF Reflow tool
π¦ SYNOPSIS π¦
k2pdfopt [opts] <input pdf/djvu | folder>
π DESCRIPTION π
So basically k2pdfopt tries to optimize your PDF (or DJVU) files β especially the two-column ones, you know the vibe β so they actually look good on a Kindle (or any other mobile reader / smartphone, we don't discriminate π«Ά). The way it does this is by hunting for rectangular regions inside the file and re-paginating them with no margins and no excess white space. Iconic behavior honestly.
It works on any PDF or DJVU (.djvu) file, but it assumes the page has a mostly-white background. And ngl, native PDF files (the ones that aren't scanned) work best. β¨
If you hand it a folder, here's the tea: k2pdfopt first looks for bitmaps in that folder, and if it finds any, it converts those bitmaps into a PDF as if they were pages of a PDF file. If there are no bitmaps in the folder but there are PDF files in there, then each PDF file gets converted in sequence. π
Output files are always .pdf, and by default they get _k2opt added to the source name (peep the -o option if you wanna pick your own output name π).
π§ Environment variable π§
You can also slide command-line options in through the environment variable K2PDFOPT, like so:
set K2PDFOPT=-ui- -x -j 0 -m 0.25
And listen β options given on the command line take precedence over the ones living in the K2PDFOPT environment variable. command line stays winning, periodt. π
π OPTIONS π
ngl bestie you might not even have to read this whole thing β just run k2pdfopt with no options at all and use the interactive menu to pick what you want. main character move fr fr. π
-?[-] [pattern]β Show [don't show] usage only, no file processing at all.
If you give a pattern, only the options with text matching that pattern get shown. The pattern can use * as a wild card, e.g. -? -col. Use -?- to turn usage off. Combine it with -ui- and you get something you can redirect straight to a file. πΎ
-a[-]β Turn on [off] text coloring (that's the ANSI color codes) in the screen output. Default is on.-ac[-] [<aggressiveness>]β Auto crop. For books or papers with those dark edges from copying artifacts, this option tries to automatically crop out the dark regions so k2pdfopt can process the source file correctly. The<aggressiveness>factor goes from0to1. Higher = more aggressive cropping. π€
Default if not specified is 0.1. See also -m.
Default value is off (-ac-).
Heads up: autocropping does not work on cropped regions created with-cbox. See-dwfor a whole discussion about this.
-as[-] [<maxdeg>]β Attempt to automatically straighten tilted source pages. π§
Will rotate up to +/-<maxdegrees> degrees if a value is specified, otherwise it defaults to 4 degrees max. Use -1 to turn off. Default is off (-as -1 or -as-). Note that autostraighten does not work on cropped regions.
See -dw for a discussion about this.
-author <author>β Set the author metadata / property of the PDF output file(s). Default is to use the author of the source document (-author "").-bmp[-] <pageno>β Generate [do not generate] a bitmap rendering of converted page number<pageno>and write it to the filek2pdfopt_out.png. If you use this option, no other files are written β like, the complete conversion is NOT done, ONLY the bitmap file gets written. If-smis also specified, then the bitmap is of marked source page<pageno>. If-bmp-, then<pageno>is not necessary. Default is-bmp-.-bp[+|-|--] [m|<inches>]β Break [do not break] output pages at the end of each input page. πβοΈ
Default is -bp-. If a numeric value goes after -bp, then instead of breaking the output page at the end of each input page, a gap of that many inches gets inserted, e.g. -bp 1 will insert a 1-inch gap between the contents of each input page. Special option -bp+ will break the pages at the green boundaries between regions as marked by the -sm option (see -sm). If bookmark information is available and -toc is specified (on by default), page breaks will be inserted in the converted file at each bookmark unless -bp-- is specified. If "-bp m" is specified, then a page break is inserted after each major (red-box) section. This can help prevent text selection overlap problems in native output mode. See also -toc, -bpl.
-bpc <nn>β Set the bits per color plane on the output device to<nn>. The value of<nn>can be1,2,4, or8. The default is4to match the kindle's display capability. This is ignored if the-jpgoption is specified.-bpl <srcpagelist>β Insert a page break in the destination file before each source file page listed in<srcpagelist>. This has the same format as the-poption. See also-p,-bp,-toc,-toclist. Default is no page list. Example:-bpl 10,25,50,70,93,117,143.
This automatically sets -bp to it's default value (-bp-).
-bpm[<type>] <color>β Set a page break mark type and color. This option lets you put colored marks in the PDF file to specify where to break pages or where to avoid page breaks.<type>is either1to force a page break or2to prevent a page break until the next mark.<color>is an R,G,B triplet,0-1for each color component, no spaces. For example, to break the page wherever the source file has a green dot or short green horizontal line:-bpm1 0,1,0. Use<color>=-1to clear. If you omit the<type>,1is assumed. π’-c[-]β Output in color [grayscale]. Default is grayscale.-cbox[<pagelist>|u|-] <cropbox>β Similar to the-gridoption, but this one lets you specify exact crop boxes from the source page which then get processed as major (red-box) regions. These regions can then become individual output pages, or they can be processed further (searched for columns, re-flowed, etc.) depending on what other options you've selected. By default, they are processed further, just like every other major region.
You may specify the -cbox option multiple times to crop out different parts of each source page, with each crop being treated as a major region. See the -mode command. To have each crop box become a new page in the output file, for example, use -mode crop, e.g.
k2pdfopt myfile.pdf -mode crop -cbox 2in,3in
<cropbox> has the format <left>,<top>,<width>,<height> where all values are specified from the upper-left corner of the source page, with units, like the -w and -h options β except that the default units for -cbox are inches. If only <left> and <top> are specified, then <width> and <height> extend to the edge of the page.
Example:
-cbox 1in,1in,6in,9in
(same as -cbox 1,1,6,9).
This specifies a crop box that is 6 x 9 inches and which has an upper left corner which is 1 inch from the left and top of the source page.
Use -cbox- to clear all cropboxes, which defaults back to processing every page without any crop boxes.
You can use a page list, <pagelist>, to specify on which pages to apply the cropboxes.
Examples:
-cbox5-51o
applies the cropbox on pages 5,7,9,...,51.
('o' = odd. Use 'e' for even.)
-cbox1,2-5,13,15
applies the cropbox on pages 1,2,3,4,5,13, and 15.
-cboxc <cropbox>
applies <cropbox> to the cover image.
(see -ci option.)
Be sure not to put a space between -cbox and the page list. π
Use -cboxu to set a crop box for all unspecified pages.
E.g. -cbox1-10 <cbox1> -cboxu <cbox2> will apply <cbox1> to all pages 1 to 10 and <cbox2> to all other pages.
The default is no crop boxes (-cbox-). See also -m, -ac.
USAGE NOTE: Once you specify-cboxat least one time, only the crop boxes you specify (and any associated page ranges) are processed/converted by k2pdfopt. No other pages or regions are processed. So if you want to specify a special cropbox for the first page, for example, but then have all remaining pages treated entirely, you must specify this:-cbox1 ... -cboxu 0,0(-cboxu 0,0applies a full-page cropbox to all other pages.u= unspecified.)
The -cbox2- 0,0 will set the cropbox for pages 2 and beyond to the full page size.
See also: -ibox.
-cg <inches>β Minimum column gap width in inches for detecting multiple columns. Default =0.1inches. Setting this too large will give very poor results for multicolumn files. See also-cgmax. π-cgmax <inches>β Max allowed gap between columns in inches. If the gap between two regions exceeds this value, they will not be considered as separate columns. Default =1.5. Use-1for no limit (disable). See also-cg.-cgr <range>β Set column-gap range,0-1. This is the horizontal range over which k2pdfopt will search for a column gap, as a fraction of the page width. E.g.-cgr 0.5will search from 0.25 to 0.75 of the page width for a column gap.
Set this to a small value, e.g. 0.05, to only search for column breaks in the middle of the page. Default = 0.33.
-ch <inches>β Minimum column height in inches for detecting multiple columns. Default =1.5inches.-ci[-] <imagefile>β Specify a cover image for the first page of the converted PDF.<imagefile>can be a bitmap file (png or jpg) or can be a page from a PDF file, e.g.myfile.pdf[34]would use page 34 ofmyfile.pdf. You can just specify an integer, e.g.-ci 50to use page 50 of the source file being converted as the cover page. Default is-ci-, which is no cover image.
NOTE: -ci only works with bitmapped output β it does not (yet) work with native PDF output.
-cmax <max>β Set max contrast increase on source pages.1.0keeps contrast from being adjusted. Use a negative value to specify a fixed contrast adjustment. Def =2.0.
See also -er.
-col <maxcol>β Set max number of columns.<maxcol>can be1,2, or4. Default is-col 2.-col 1disables column searching.
β¨ okay that's the first chunk bestie, and there's more coming β don't go anywhere π
-colorbg(or-colorfg)<hexcolor>|<bitmap>[,<hexcolor>|<bitmap>[,...]] β bestie, this one remaps a color for you π . You're telling k2pdfopt to map the color white (that's the background color, when you use-colorbg) or the color black (the text color, when you use-colorfg) to your<hexcolor>. And<hexcolor>is just a 6-digit hexRRGGBBrepresentation of a color β likefffffffor all white,000000for all black,ff0000for bright red, etc. β¨
Okay so important detail: if <hexcolor> is not a grayscale color, the -c (color output) option gets turned on automatically, no cap. And this option only works with bitmapped output (not native β see -n, iykyk). Grayscale colors between black and white get linearly interpolated between the -colorbg and -colorfg colors you specified. And if your source document has colors, only (mostly) grayscale pixels are affected if you put ! before the color, e.g. -colorbg !ffffd0.
You can also hand it a bitmap, like -colorbg myfile.jpg β in that case the bitmap gets tiled in as the background π.
And if you drop a comma-delimited list of colors (or bitmaps)? Then consecutive rows of text get colored with the consecutive colors. That's a whole way to make rows of text easier to follow, e.g. -colorfg ff0000,00 colors alternate rows of text red and black. Iconic.
Default is -colorbg "" and -colorfg "" (no mappings).
-comax<range>β stands for Column Offset Maximum β¨. The<range>you give is a fraction of the width of a single column, and it says how much the column divider can move around and still have the columns considered contiguous. Set it to-1to revert back to how columns were treated in k2pdfopt v1.34 and before.
Default = 0.3.
-crgh<inches>β sets the min height of the blank area that separates regions with different numbers of columns. Lowkey important for column vibes.
Default = 1/72 inch.
-d[-]β turn on [-d] / off [-d-] dithering for bpc values < 8. See-bpc.
Default is on.
-de<size>β defect size, in points. For scanned documents, marks or defects smaller than this size get ignored when bounding rectangular regions. Fun fact: the period at the end of a sentence is typically over 1 point in size. The default is1.0.-dev<name>β select a device profile (this sets width, height, dpi, and corner marking for selected devices). Currently the selection is limited.<name>just has to have enough characters to uniquely pick the device. Use-dev ?to list the devices π
Default is -dev kindle2.
-dpi<dpival>β same as-odpi. That's it, that's the whole thing.-dr<value>β display resolution multiplier. Default =1.0. Using a value greater than 1 should improve the resolution of the output file (but it will make it larger in file size, so like, pick your poison π).
E.g. -dr 2 will double the output DPI, the device width (in pixels), and the device height (in pixels).
-ds<factor>β override the document size with a scale factor. E.g. if your PDF reader says the PDF file is 17 x 22 inches and it should actually be 8.5 x 11 inches, use-ds 0.5. Default is1.0.-dw[-][<fitorder>] β de-warp [-dw] / do not de-warp [-dw-] pages (this uses Leptonica de-warp algorithms). Default is not to de-warp. It does not work for native mode output. The optional<fitorder>specifies the fit order for the dewarping curves. Can be2,3, or4.
Default is 4.
[Advanced: you can actually make the fit order a two-digit code. E.g.-dw 24will use 4th-order on each row of text but only 2nd-order for columns of displacement (see leptonicadewarpFindVertDisparity()indewarp2.c)]
Note: de-warping, like auto-straighten and auto-crop, is intended for entire pages. It does not work on cropped areas. If you want it to work on cropped areas, you should run k2pdfopt in two passes β first to create selected crop areas (e.g. -mode crop), then to apply dewarping. β¨
Require k2pdfopt built with leptonica.
-ehl<n>β same as-evl, except it erases horizontal lines instead of vertical lines. See-evl. Default is-ehl 0.-er<n>β use the erosion filter on source bitmaps. Makes the text look darker. A larger value of<n>makes the text thicker/darker. Try-er 1or-er 2. Default is0(no erosion filtering).
Use a negative value for <n> to do the erosion before the contrast adjustment is applied. Use a positive value to do the erosion after the contrast adjustment is applied. Heads up bestie: this option may magnify scanning defects, so you might want to combine it with the -de (defect removal) option π.
It has no effect in native mode output. See also -de, -g, -cmax.
-evl<n>β detects and erases vertical lines in the source document which may be keeping k2pdfopt from correctly separating columns or wrapping text, e.g. column dividers. If<n>is zero, this is turned off (that's the default). If<n>is1, only free-standing vertical lines are removed. If<n>is2, vertical lines are erased even if they are the sides of an enclosed rectangle or figure, for example. π-f2p<val>β fit-to-page option. The quantity<val>controls fitting tall or small contiguous objects (like figures or photographs) to the device screen. Normally these are fit to the width of the device, but if they're too small or too tall, then if<val>=10, for example, they're allowed to be 10% wider (if too small) or narrower (if too tall) than the screen in order to fit better. Use-1to fit the object no matter what. Use-2as a special case β all "red-boxed" regions (see-smoption) are placed one per page. π₯
Use -f2p -3 to fit as many "red-boxed" regions as possible on each page without breaking them across pages (see -mode concat).
Default is -f2p 0. See also -jf, -fr.
Note:-f2p -2will automatically also set-vb -2to exactly preserve the spacing in the red-boxed region. If you want to compress the vertical spacing in the red-boxed region, use-f2p -2 -vb -1.
-fc[-]β for multiple column documents, fit [-fc] / don't fit [-fc-] columns to the width of the reader screen regardless of-odpi.
Default is to fit the columns to the reader.
-fr[-]β figure rotate β rotates wide-aspect-ratio figures to landscape so that they best fit on the reader page. Default is not to rotate. See also-f2p.-fs<points>[+] β the output document is scaled so that the median font size in the converted file is<points>points. If the<points>value is followed by a+, the scaling is adjusted for every source page, otherwise the font size is only adjusted once, based on the median font size for the entire source document. The default is-fs 0, which turns off scaling based on font size. And psst β the use of-fsoverrides the-magsetting. π«Ά-g<gamma>β set the gamma value of output bitmaps. A value less than1.0makes the page darker and may make the font more readable. Default is0.5. Has no effect with native-mode output. See also-er,-cmax.-grid<C>x<R>[x<O>][+] β grid the source page into<C>columns by<R>rows with<O>percent overlap. No regard will be made for trying to break the page between columns or rows of text, so like, it's giving chaotic energy on purpose. If a+is specified, the destination page order will go across and then down; otherwise it will go down and then across. To turn off gridding, specify a zero value for the columns or for the rows. Default is no gridding. The default overlap is2%. Example:-grid 2x2x5. By default, gridding also sets the following options, which can be overridden by following the grid option with other command options:-n -wrap- -f2p -2 -vb -2 -col 1. For example, if you want a column search done on each grid piece, you can put this:-grid 2x2 -col 2. See also-cbox.-gs[-][-]β force use of Ghostscript instead of MuPDF to read PDFs. k2pdfopt has built-in PDF translation (via the MuPDF library) but will try to use Ghostscript if Ghostscript is available and the internal (MuPDF) translation fails (which virtually never happens). You can force Ghostscript to be used with this-gsoption. Use-gs-to use Ghostscript only if MuPDF fails. Use-gs--to never use Ghostscript. Download ghostscript athttp://www.ghostscript.com.-gtc<inches>β threshold value for detecting column gaps (expert mode, bestie π). This sets how many of the pixels in the column shaft can be non-white (total height of a line crossing the shaft in inches). See also-gtr. Default =.005.-gtr<inches>β threshold for detecting gaps between rows (expert mode). This sets the maximum total black pixels, in inches, on average, that can be in each row of pixels before the gap is no longer considered a gap. A higher value makes it easier to detect gaps between rows of text. But careful β too high of a value may inadvertently split figures and other graphics π.
Default = 0.006. See also -rsf.
-gtw<inches>β threshold for detecting word gaps (expert mode).
See -gtr. Default = .0015.
-gui[-]β use [-gui] / don't use [-gui-] graphical user interface (MS Windows only). If k2pdfopt is started from a console (command-line), the default is not to launch the gui unless there are no command-line options given. If k2pdfopt is launched via its icon, then the default is to launch the GUI.-guimin[-]β start the k2pdfopt GUI minimized. Def = not minimized.-h<height>[in|cm|s|t|p|x] β set height of output device in pixels, inches, cm, source page size (s), trimmed source region size (t), pixels (p), or relative to the OCR text layer (x).
The default units are pixels (p), and the default value is 735 (the height of the Kindle 2 screen in pixels).
Examples:
-h 6.5in
Sets the device height to 6.5 in (using the
output dpi to convert to pixels--see -dpi).
-h 1.5s
Sets the device height to 1.5 times the source
page height (same as -h -1.5).
-h 1tβ sets the device height to literally whatever the trimmed page height is. Pro tip: pair-mode copywith-h 1tand boom, your output page height == the crop box height. β¨-h 0.5xβ sets the device height to half the height of the box that exactly surrounds the OCR text layer on the source page. snug.
see also -w, -dpi, -dr.
-hy[-]β turn on [off] hyphen detection/elimination while wrapping text. Default is on. no more awkward "hy-phen" splits bestie π-iβ echoes info about the source file (PDF only). heads up: this disables all other processing. it's giving "just tell me about the file and nothing else" π«Ά-ibox[<pagelist>|-|u] <cropbox>β same as-cbox(go read-cbox), except these boxes get ignored by k2pdfopt. how? by whiting out the boxes in the source bitmap. for native output, the area inside the-iboxwon't affect how the source file is parsed, but it may still be visible in the output file. default is no iboxes (-ibox-). see also-cbox.-idpi <dpi>β sets pixels per inch for the input file. use a negative value and it acts as a multiplier on the output dpi β e.g.-2sets the input file dpi to twice the output file dpi (peep-odpi). default is-2.0.-j -1|0|1|2[+/-]β set output text justification.0= left,1= center,2= right. add a+to attempt full justification, or a-to explicitly turn it off. the default is-1, which tells k2pdfopt to try and maintain the justification of the document as it already is. see also-wrap.-jf 0|1|2 [<inches>]β set figure (tall region) justification. if a figure has left or right margins available, this lets you justify it differently than the text. like, you can center figures with-jf 1. π wanna set a minimum height for figures (i.e. the minimum region height where this justification kicks in)? tack it on at the end β e.g.-jf 1 1.5centers any region taller than 1.5 inches. default is 0.75 inches for the minimum height, and to use the same justification on figures as the rest of the document (-jf -1). see also-f2pto fit small or tall figures to the page.-jfc[-|+]β attempt [do not attempt] to keep figure captions joined with their figures. if you specify-jfc+, k2pdfopt will also try to detect figure captions in multi-column documents. this is not done by default because k2pdfopt will sometimes (more often than not, in my experience π) incorrectly choose the multi-column layout if it's also trying to detect what's a figure caption. see also-cg,-cgmax,-cgr,-crgh. default =-jfc.-jpg [<quality>]β use JPEG compression in the PDF file with quality level<quality>(def=90). lower quality value β smaller file. see also-png. > β οΈ heads up: using-jpgis incompatible with the-bpcoption. pick one bestie.-l <lang>β see-ocrlang.-lang <lang>β see-ocrlang.-ls[-][pagelist]β set output to be in landscape [portrait] mode. default is-ls-(portrait). if you add an optional pagelist, only those pages are affected β every other page gets done the opposite way. e.g.-ls1,3,5-10makes source pages 1, 3 and 5 through 10 landscape. π-m[l|t|r|b] <val>[<units>][,<val>[units][,...]]β set global crop margins for every page. give more than one value (comma-delimited, no spaces in between) and the order is left, top, right, bottom, e.g.-m <left>,<top>,<right>,<bottom>. you can also use the way more powerful-cboxoption to do this exact same thing. default units are inches. for the available units and what they mean, go look at-h.
Examples, bestie:
-m 0.5cmβ sets all margins to 0.5 cm.-m 0.5cm,1.0cmβ sets the left margin to 0.5 cm and all the other margins to 1.0 cm.-m 0.2in,0.5in,0.2in,0.5inβ sets the left and right crop margins to 0.2 inches and the top and bottom to 0.5 inches.-mt 1cmβ sets the top margin to 0.5 cm.-m -0.1x,-0.1x,1.1x,1.1xβ with the'x'unit the behavior is a lil different. instead of specifying the widths of each margin, you specify the position of the crop box relative to the OCR text layer in the source file, where0x,0x,1x,1xwould exactly bound the OCR text layer.
The default crop margins are 0 inches.
π NOTE: the default was 0.25 inches for all margins before v1.65.
see also -cbox and -ac to autocrop scanning artifacts.
-mag <value>β magnify the converted document (text) size by<value>. default is-mag 1(no magnification). see also-fs.-mc[-]β mark [don't mark] corners of the output bitmaps with a small dot to prevent the reading device from re-scaling. default = mark. π―-mode <mode>β a shortcut that sets multiple options at once, determining the basic way k2pdfopt will behave.
Available modes are:
copyβ same as-n- -wrap- -col 1 -vb -2 -w 1s -h 1s -dpi 150 -rt 0 -c -t- -f2p -2 -m 0 -om 0 -pl 0 -pr 0 -pt 0 -pb 0 -mc-. makes k2pdfopt behave exactly like my pdfr program β source pages are simply copied to the output file, but rendered as bitmaps. no trimming or re-sizing is done. can also use-mode pdfr.- Note 1: use
-mode copy -nif you want an exact copy (output in native mode). - Note 2: the default gamma and contrast settings are not reset by
-mode copy. if you want a perfect copy, do this:-mode copy -gamma 1 -cmax 1
- Note 1: use
fpβ also can usefitpage. same as-n -wrap- -col 1 -vb -2 -f2p -2 -t.fwβ same as-n -wrap- -col 1 -vb -2 -t -ls. makes k2pdfopt behave like sopdf's "fit width" option. can also use-mode sopdf.2colβ same as-n -wrap- -col 2 -vb -2 -t. optimizes for a 2-column scientific article with native PDF output. πtmβ trim margins β same as-mode copy, but sets the output to be trimmed to the margins and the width and height of the output to match the trimmed source pages. also uses native mode. equivalent to-n -wrap- -col 1 -vb -2 -f2p -2 -t -w 1t -h 1t -rt 0 -c -m 0 -om 0 -pl 0 -pr 0 -pt 0 -pb 0 -mc-. can also use-mode trim.cropβ used with the-cboxoption, puts each cropped area on a separate page, untrimmed, and sizes the page to the cropped region. same as-wrap- -col 1 -vb -2 -w 1t -h 1t -t- -rt 0 -c -f2p -2 -m 0 -om 0 -pad 0 -mc- -n concat. keeping the output pages the same size as the source pages, fit as many crop-boxed regions on the output pages as possible without breaking them across pages. equivalent to:-n -wrap- -col 1 -vb -2 -t- -f2p -3 -fc- -w 1s -h 1s -ocrdef. default k2pdfopt mode:-wrap -n- -col 2 -vb 1.75 -dev k2 -rt auto -c- -t -f2p 0 -m 0 -om 0.02 -ls-.concatβ keeping the output pages the same size as the source pages, fit as many crop-boxed regions on the output pages as possible without breaking them across pages. equivalent to:-n -wrap- -col 1 -vb -2 -t- -f2p -3 -fc- -w 1s -h 1s -ocr-.defβ default k2pdfopt mode:-wrap -n- -col 2 -vb 1.75 -dev k2 -rt auto -c- -t -f2p 0 -m 0 -om 0.02 -ls-.
you can modify modes by overriding their options after specifying the mode, e.g. -mode fw -vb -1. so much power tbh π
-n[-]β use "native" PDF output format.
β οΈ NOTE: if you want native PDF output, it's probably best to use a-modeoption like-mode fitwidthor-mode 2col, both of which automatically turn on native PDF output and optimize other settings for it.
Native PDF output preserves the native source PDF contents β i.e. the output PDF file is not rendered as a sequence of bitmapped pages like in the default k2pdfopt output mode. instead, the source PDF's native content is used along with additional PDF instructions to translate, scale, and crop the source content. with native PDF output, if the source file has selectable text, the text stays selectable in the output file. the output file can also be zoomed without loss of fidelity. this may also result in a smaller output file (but not always). by default, native PDF output format is turned off. see also -mode.
NOTES, bestie, read them all:
- Native PDF output cannot be used with text wrapping on (see
-wrapoption). turning it on will disable text wrapping. - Native PDF output is not recommended for source files which are scanned (there's no benefit unless the scanned document includes a layer of OCR text).
- Native PDF output is incompatible with OCR (see
-ocr), though OCR is typically not necessary if the native PDF contents are kept. turning on native PDF output will disable OCR. - Native PDF output can only be used with PDF source files (it does not work with DJVU source files).
- Contrast adjust, gamma correction, and sharpening are disabled with native PDF output.
- It's recommended that you use
-vb -2with native PDF output, particularly if you're having difficulty selecting/searching text in the output PDF file. - This option works well with
-mode fw,-mode 2col, or with the-gridoption. it's used by default in those cases.
-neg[-|+]β inverse [don't inverse] the output images (white letters on black background, or "night mode" π). if-neg+, inverts all graphics no matter what. if just-neg, attempts to invert text only and not figures. default =-neg-.
see also -colorbg and -colorfg.
-ng<gap>β sets the gap between your notes and the main text in the output doc π«Ά.<gap>defaults to inches but it can take other units too (peep-hfor a lil example). Wanna know how to actually turn notes processing on? go look at-nland-nr. Default is-ng 0.2.-nl[<pages>] [<leftbound>,<rightbound>]-nr[<pages>] [<leftbound>,<rightbound>]β bestie, this is for when your source doc has notes chillin' in the left (-nl) or right (-nr) margins. You can point at specific pages for the notes with<pages>(same format as-cboxor-p). And if you hand it<leftbound>,<rightbound>, those say what fraction of the page width to go hunting in for the break between the notes and the main page. Like,-nl 0.15,0.25will look for the boundary between the notes and the text somewhere between 15% and 25% of the way across the source page. Use-nl-to turn off all processing of notes in the margins (that's the default, btw). Default values for<leftbound>and<rightbound>are0.05to0.35for-nl, and0.65to0.95for-nr.
Notes in the margins get treated differently than other "columns" of text β they'll be interspersed with the text in the adjacent column of main text. Also heads up: -nr... or -nl... will also set -cg to 0.05 β¨.
-nt<nthreads>β use<nthreads>parallel threads when you're OCR-ing a doc with the Tesseract OCR engine (GOCR is not thread safe, periodt). This can be a significant speed glow-up when you're using Tesseract OCR π₯. But ngl, a higher number is not always faster β you gotta experiment with your own system to find the optimum. A negative value gets interpreted as a percentage of available CPUs. The default is-50, which tells k2pdfopt to use half of the available CPU threads. Some performances the author measured:
OCR Speed
O/S CPU Nthreads improvement
----------------------------------------------------------
Win 10 x64 Core i5 2 (default) 1.5x
Win 10 x64 Core i5 3 1.6x
Win 10 x64 Core i5 4 1.8x
----------------------------------------------------------
Win 10 x64 Core i7 2 1.8x
Win 10 x64 Core i7 3 2.4x
Win 10 x64 Core i7 4 (default) 2.5x
Win 10 x64 Core i7 5 2.8x
Win 10 x64 Core i7 6 2.7x
Win 10 x64 Core i7 7 2.7x
Win 10 x64 Core i7 8 2.6x
----------------------------------------------------------
Linux x64 Core i5 2 (default) 1.9x
Linux x64 Core i5 3 2.6x
Linux x64 Core i5 4 2.7x
----------------------------------------------------------
Linux x64 Xeon E52690v2 2 1.9x
Linux x64 Xeon E52690v2 4 3.5x
Linux x64 Xeon E52690v2 6 5.1x
Linux x64 Xeon E52690v2 8 6.6x
Linux x64 Xeon E52690v2 10 (default) 8.7x
Linux x64 Xeon E52690v2 14 9.5x
Linux x64 Xeon E52690v2 20 10.2x
----------------------------------------------------------
Interestingly, Linux seems to have much better multithreading performance than Windows π. The author suspects the OS/X results are similar to the Linux results.
NOTE:-nthas no effect if you select-ocrd cor-ocrd p. See-ocrd.
Requires k2pdfopt built with OCR lib π.
-o<namefmt>β sets the output file name using<namefmt>. Here's the substitution tea π΅:%sgets replaced with the full name of the source file minus the extension.%bgets replaced by the base name of the source file minus the extension.%fgets replaced with the folder name of the source file.%dgets replaced with the source file count (starting with1).
The .pdf extension will be appended if you don't specify an extension. E.g. -o out%04d.pdf will result in output files out0001.pdf, out0002.pdf, ... for the converted files. Def = %s_k2opt.
BITMAP OUTPUT: for output to bitmaps, you can put -o .png or -o .jpg (see -jpeg for the quality setting).
MORE DETAIL: if <namefmt> ends in .jpg or .png, the output will be in the JPEG or PNG bitmap format, respectively β one bitmap per page π¦. If your <namefmt> has no %d in it, then %04d will be appended. If <namefmt> has only one %d, it gets substituted with the page number. If it has two %d's, the first gets the file count and the second gets the page number. Example: if the source PDF is myfile.pdf, then -o %s%03d.png would create myfile001.png, myfile002.png, etc., for each page of the PDF.
-ocr[-][g|t|m]β attempt (-ocr) [don't attempt (-ocr-)] to use optical character recognition (OCR) so you can embed searchable text into the output PDF doc π . If it's followed bytorg, that specifies the OCR engine to use (tesseractorgocr). If followed bym, and the PDF document has text in it, then the MuPDF engine is used to extract the text (sort of a virtual OCR, iykyk). If-ocris specified with no argument,tesseractis used. If tesseract fails (e.g. no language files found), GOCR is used. The overall default operation of k2pdfopt is-ocr m. See also-ocrvisand-ocrhmax.
NOTE: turning on OCR will disable native PDF output.
DISCLAIMER: the main intent of OCR isn't to improve the visual quality of the text at all β at least not the way k2pdfopt does it. OCR is most useful on scanned PDFs that don't have selectable text to begin with, but using OCR with k2pdfopt on such documents doesn't change the look of the output PDF file at all. The OCR text is simply placed invisibly over the scanned text so that you appear to be able to select the scanned text (when, in fact, you are selecting the invisibly placed OCR text π). So the only time you will even notice the OCR errors is if you try to search for a word and can't find that word because the OCR of that word is incorrect, or if you copy a selection of the OCR text and paste it into something else so that you can actually see it.
-ocrcol<n>β if you're simply processing a PDF to OCR it (e.g. if you're using the-mode copyoption) and the source document has multiple columns of text, set this value to the number of columns to process (up to4). Default is to use the same value as-col.-ocrd w|l|c|pβ sets the OCR detection type for k2pdfopt and Tesseract.<type>can be word (w), line (l), columns (c), or page (p). Default is line.- For
-ocrd w, k2pdfopt locates each word in the scanned document and passes individual words to Tesseract for OCR conversion. This was the only type of detection before v2.42 but is not an optimal OCR conversion method when using Tesseract. - For
-ocrd l, k2pdfopt passes each line of the converted file to Tesseract for conversion. This typically gives better results than-ocrd wsince Tesseract can better determine the text baseline position with a full line. - For
-ocrd c, k2pdfopt detects each column of the converted file and passes that to Tesseract for conversion. - For
-ocrd p, k2pdfopt passes the entire output page of text to Tesseract and lets Tesseract parse it for word positions. Tesseract has done considerable code development for detecting words on pages (more than k2pdfopt), so this should also be a reliable way to create the OCR layer β¨.
- For
One drawback to -ocrd c or -ocr p is that there is no benefit to using the OCR multithreading option (see -nt) π.
Requires k2pdfopt built with leptonica.
-ocrhmax<in>β sets the max height for an OCR'd word in inches. Any graphic exceeding this height will not be processed with the OCR engine. Default =1.5. See-ocr.-ocrlang<lang>|?β selects the Tesseract OCR Engine language π. This is the root name of the training data, e.g.-lang engfor English,-ocrlang frafor French,-ocrlang chi_simfor simplified Chinese. You can also use-l. The default language is whatever is in your Tesseract trained data folder β if you have more than one.traineddatafile in that folder, the one with the most recent time stamp is used.
NOTE 1: use -ocrvis ? to see the list of Tesseract language files in your Tesseract data folder.
NOTE 2: using the-ocrvis toption will not show the OCR text correctly for any character above unicode value255, since k2pdfopt does not use any embedded fonts β but the text will convert to the correct Unicode values when copy / pasted.
NOTE 3: Tesseract allows the specification of multiple language training files, e.g. -ocrlang eng+fra would specify English as the primary and French as the secondary OCR language. In practice the author has not found this to work very well π. Try multiple languages in different orders.
Requires k2pdfopt built with leptonica.
-ocrdpi<dpi>β sets the desired dpi of the bitmaps passed to the OCR engine OR sets the desired height of a lower case letter (e.g.'e') in pixels π. If<dpi>is positive, it's interpreted as dpi. If<dpi>is negative, the absolute value is interpreted as a lowercase letter height in pixels. Any bitmapped text sent to the OCR engine will be downsampled (if too large) so that the appropriate dpi or lowercase letter size is achieved.
The default is 300 because the author found this works best empirically for Tesseract v4.0.0 English OCR with font sizes in the range 8 - 15 pts π. Use a lower value if the font size in your document is larger than 15 - 20 pts. Or use -ocrdpi -24 if you have a wide range of font sizes. Use -ocrdpi 0 to disable any downsampling.
-ocrout[-]<namefmt>β Write [or don't write, if you slap that-on there] the UTF-8 OCR text output to a file called<namefmt>. Wanna know how<namefmt>does its thing? Peep the-ooption, bestie, it's all explained there. The default extension is.txt. And the default is, like, no output at all. π-ocrsort[-]β So when a PDF already comes with its own OCR/Text layer, this bad boy orders that OCR text layer by where it sits on the page. Honestly you shouldn't need this unless the OCR layer was generated really badly β like, it's giving chaos. Default is-ocrsort-(off). π«Ά-ocrsp[+|-]β When it's generating the OCR layer, this makes it do a whole entire row of text at once, with spaces between every word. By default (-ocrsp-), each word gets placed separately in the PDF's OCR layer. And that causes drama with text selection in some readers β like, you literally can't select individual words. Using-ocrsp-may fix behaviour like that, but ngl it'll give you less accurate word placement, because k2pdfopt isn't out here trying to exactly match the font the document uses. Use-ocrsp+to allow more than one space between each word in that row of text, so the selection position can be optimized. β¨-ocrvis<s|t|b>β Set the OCR visibility flags, periodt. Dropsto show the source doc,tto show the OCR text, and/orbto put a box around each word. Default is-ocrvis s. Wanna show both the source document AND the OCR text overlayed on top? That's-ocrvis st. See also-ocr. And see also-ocrlang(there's a note about-ocrvis tover there). π-odpi<dpi>β Set the pixels per inch of the output screen (default is 167). See also-dr,-w,-h,-fc. You can also use-dpifor this, same vibe.
See also -fs, -mag.
-om[b|l|r|t]<val>[<units>][,<val>[units][,...]]β Set the blank-area margins on the output device. Works basically exactly like the-moption does β go read-mfor the tea on the syntax. Default = 0.02 inches.
Heads up tho: the s, t, and x units for -om all behave the same and scale to the device size. Like, -om 0.1s will make the device screen margins 0.1 times the device width (for the left and right margins) or height (for the top and bottom margins) of the output device screen. Math but make it cute. πΈ
-ow[-][<mb>]β Sets the minimum file size (in MB) where overwriting the file will not happen without prompting you first. Set it to-1(or just-owwith no value) to overwrite all files with zero prompting β living dangerously, love that for you. Set it to0(or just-ow-) to prompt for any overwritten file. Default =-ow 10, which means any existing file over 10 MB won't get overwritten without a prompt. See also the-yoption. π₯-p<pagelist>β Specify which pages to convert.<pagelist>must not have any spaces in it, okay? Like-p 1-3,5,9,10-would do pages 1 through 3, page 5, page 9, and pages 10 through the very end. The letterseandocan denote even and odd pages, e.g.
-p o,e Process all odd pages, then all even ones.
-p 2-52e,3-33o
Process 2,4,6,...,52,3,5,7,...,33.
Overridden by the -px option. See -px.
-pad<padlist>β A cute little shortcut for-pl,-pt,-pr,-pb. E.g.-pad 15,10,13,20is the same as-pl 15 -pt 10 -pr 13 -pb 20. Also, using-pad 15will set all the pads to 15, for example. One number, all the vibes. π-p[b|l|r|t]<nn>β Pad the [bottom|left|right|top] side of the destination bitmap with<nn>rows. Defaults = 4 (bottom), 0 (left), 3 (right), and 0 (top). Example:-pb 10. This is typically only used on certain devices to get the page to come out just right. For setting margins on the output device, use-om. See also-pad.-pngβ (Default) Use PNG compression in the PDF file. See also-jpeg. π-ppgs[-]β Post process [or do not post process] with ghostscript. This takes the final PDF output and runs it through ghostscript'spdfwritedevice (assuming ghostscript is even available, bestie). The benefit? All the "invisible" and/or overlapping text regions (outside cropping areas) get completely removed, so text selection capability gets improved. The actual ghostscript command used is:
gs -dSAFER -dBATCH -q -dNOPAUSE -sDEVICE=pdfwrite
-dPDFSETTINGS=/prepress -sOutputFile=<outfile>
<srcfile>
The default is to not post process with ghostscript.
-px<pagelist>β Exclude pages from<pagelist>. Overrides the-poption. Default is no excluded pages (-px -1).-r[-]β Right-to-left [left-to-right] page scans. Default is left to right.-rls[+|-]β Restore [+] or don't restore [-] the last command-line settings from the environment variableK2PDFOPT_CUSTOM0. The default (-rls) is to restore the settings if there are no other command-line options specified when running (from either the command line or theK2PDFOPTenv var), unless those options are-guior specify a file name. π¦-rsf<val>β Row Split Figure of merit (expert mode, ooo fancy). After k2pdfopt has looked for gaps between rows of text, it'll check to see if there appear to be missed gaps (e.g. if one row is twice the height of all the others). Increasing this value makes it harder for k2pdfopt to split a row. Lowering it makes it easier. Default value = 20.-rt<deg>|auto[+]|aepβ Rotate the source page counterclockwise by<deg>degrees.
NOTE: If you're trying to get "landscape" output so you can turn your reader on its side, use-lsinstead of-rt. The-rtoption is meant for when your source PDF is incorrectly rotated β like if you view it on a standard PC reader and it comes up sideways. π
<deg> can be 90, 180, 270. Or use -rt auto to examine up to 10 pages of each file to determine the orientation used on the entire file (this is the default). Or use -rt aep to auto-detect the rotation of every page. If you've got different pages rotated differently from each other within one file, you can use this option to try to autorotate each source page. Use -rt auto+ to turn on autodetect even in preview mode (otherwise it's off).
See also -ls.
-s[-]β Sharpen [don't sharpen] images. Default is to sharpen. β¨-sm[-]β Show [don't show] marked source. This is a debugging tool where k2pdfopt marks the source file with the regions it finds on them and the order in which it processes them, and saves it as<srcfile>_marked.pdf. Default is not to show marked source. Red regions are found on the first pass (use-f2p -2to put each red region on a separate page). Green lines mark vertical regions affected by-vband-vs. Gray lines mark individual rows of text (top, bottom, and baseline). Blue boxes show individual words (passed to OCR if-ocris specified). π-sp[-]β For each file on the command line, just echo the number of pages β don't process. Default = off (-sp-).-t[-]β Trim [don't trim] the white space from around the edges of any output region. Default is to trim. Using-t-is not recommended unless you want to exactly duplicate the source document. π-title<title>β Set the title metadata / property of the PDF output file(s). Default is to use the title of the source document (-title ""). The<title>string will be parsed for special characters that let you substitute the file name. See the-ooption for a description of these substitutions.-to[-]β Text only output. Remove figures from output. Figures are determined empirically as any contiguous region taller than 0.75 inches (or you can specify this using the-jfoption). Use-to-to turn off (default).-toc[-]β Include [don't include] table of contents / outline / bookmark information in the PDF output, if it's available in the source file (works only for PDF source files, and only if MuPDF is compiled in). By default, a new destination page is started at each bookmark location. To disable this, see the-bpoption. If-toc-is specified, bookmark information from the source file is ignored. See also-toclist. Default is-toc.-toclist<pagelist>|<file>β Override the PDF source file's outline information (bookmarks / table of contents) with either a list of source pages or a file describing the table of contents. If you specify a list of pages, e.g.-toclist 5,10,20,40,100, then those pages are marked as Chapter 1, 2, etc., respectively. If you specify a file name, the file should be a text file formatted like this example:
1 Introduction
10 Chapter 1
+10 Chapter 1, Part A
+25 Chapter 1, Part B
++25 Chapter 1, Part B, Subsection 1
++27 Chapter 1, Part B, Subsection 2
+30 Chapter 1, Part C
50 Chapter 2
70 Chapter 3
The + indicates a sub-level heading (multiple +'s for multiple sub-levels). The first number on the line is the source page reference number. The rest of the text on the line is the name of the chapter / subheading.
Note: This option overrides-toc. To get a template from an existing PDF file, see the-tocsaveoption.
-tocsave<file>β If an outline exists in the PDF file (and-tocis specified), write that outline to text file<file>in the format required by-toclist. See-toc,-toclist. π-ui[-]β User input query turned on [off]. Default = on for linux, or if not run from the command line in Windows.-vβ Verbose output. Gimme all the details, bestie. π-vb<thresh>β Set the gap-size vertical-break threshold between regions that cause them to be treated as separate regions. E.g.-vb 2will break the document into separate regions anywhere there's a vertical gap that exceeds 2 times the median gap between lines of text. These separate regions may then be scaled and aligned independently. π₯
Special values: Use -vb -1 to preserve all horizontal alignment and scaling across entire regions (vertical spacing may still be adjusted). Use -vb -2 to exactly preserve each region (both horizontal alignment and vertical spacing β this is the value used by -mode fw, for example). The default is -vb 1.75.
-vls <spacing>β bestie, this one sets your vertical line spacing as a fraction of the text size. It's the override button for whatever line spacing the document thought it was doing.<spacing>of1= single spacing,2= double spacing, math is mathing π . If you go negative, the absolute value becomes the limiting case β like, if you set-vls -1.5, the original document's line spacing is preserved unless it exceeds 1.5 (times single spacing), at which point it gets capped. Default =-1.2. See also-vs. β¨-vs <maxgap>β this preserves up to<maxgap>inches of vertical spacing between regions in the document (those regions get marked in green when you're using the-smoption π). It has no effect if you use a negative value for-vb. The default value is0.25.
See also -vls, -vb.
-w <width>[in|cm|s|t|p]β sets the width of your output device. Default is560. See-h. π-wrap[-|+]β enables [disables] text wrapping. Default = enabled. If you go-wrap+, regions of text with lines shorter than your mobile device screen get re-flowed to fit the screen width. And heads up β if you use-wrap+, you may wanna also specify-fc-so that narrow columns of text don't get magnified to fit your device. Text wrapping disables native PDF output (see-n). See also-ws,-j,-fc,-n. π-ws <spacing>β sets the minimum word spacing for line breaking, as a fraction of the height of a lowercase'o'. Bigger value = harder to break lines. If it's negative, automatic word spacing is turned on, and that automatic spacing leans toward breaking long words between letters so your text is sure to fit the device display. Def =-0.20. The absolute value of the setting, if negative, is used as a minimum allowed value. So if you want k2pdfopt to aggressively break lines (like, break apart long words if they don't fit on a line), use a smaller absolute value, e.g.-ws -0.01. A positive value works as it did in v2.18 and before. The default value was changed from0.375in v2.18 to-0.20in v2.20. See also-wrap. π-wt[+] <thresh>β any pixels whiter than<thresh>(0-255) are treated as "white". Setting this lower can help k2pdfopt better process some poorly-quality scanned pages or pages with watermarks. β οΈ But note β the pixels that are above the<thresh>value and therefore treated as white are not actually changed to pure white (255) unless you also include the'+'. Otherwise this only sets a threshold, no pixel-touching. The default value for-wtis-1, which tells k2pdfopt to pick the optimum value for you. See also-cmax,-colorfg,-colorbg. π-x[-]β exit [don't exit β wait for<Enter>] after completion. πͺ-y[-]β assume [don't assume] "yes" to queries, like whether to overwrite a file. See also-ow. Also turns off any warning messages. (Not me silencing the warnings π)
πΈ SEE ALSO πΈ
http://www.willus.com/k2pdfopt/
π AUTHOR π
K2pdfopt is written by Willus.
This manual page was written by Yangfl for the Debian Project (but may be used by others).
okay bestie that's the whole page, we made it π«Ά this was the User Commands section, dated 2017-12-07, and the page lives as K2pdfopt(1) in the manual. go forth and convert your PDFs, you absolute main character π
β¨π
π¦ where this page comes from
- debian trixie: k2pdfopt 2.55+ds-3.1+b1 Β· AGPL-3.0-or-later
- ubuntu noble: k2pdfopt 2.55+ds-2 Β· AGPL-3.0-or-later
- ubuntu questing: k2pdfopt 2.55+ds-3.1build2
- ubuntu resolute: k2pdfopt 2.55+ds-4build1 Β· AGPL-3.0-or-later
- ubuntu stonking: k2pdfopt 2.55+ds-4build1 Β· AGPL-3.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms