1 (изменено: Rumata, 2013-08-20 12:44:14)

Тема: CMD/BAT/BASH: jpeg -> pdf

Понадобилось мне конвертировать картинки в формате JPG в PDF. Предполагается наличие соответствующих предустановленных утилит, например, из пакета Cygwin в случае использования на системе win32.

Может быть задача и глупая и простая, но, тем не менее, не могу не поделиться. Возможно, кто-то из коллег знает лучшее решение - буду рад увидеть ваше решение:


jpg2pdf ()
{
    local jpg="${1:--}";
    local pdf="${2:--}";
    jpegtopnm "$jpg" | pnmtops -noturn | ps2pdf - "$pdf"
}

Применение:

jpg2pdf filename.jpg filename.pdf
( 2 * b ) || ! ( 2 * b )

2

Re: CMD/BAT/BASH: jpeg -> pdf

Я делал нечто подобное, но под Windows, с помощью «ImageMagick»:

for %i in (*.jpg) do @"%ProgramFiles%\ImageMagick-6.3.4-Q8\convert.exe" "%~fi" -format pdf "%~dpni.pdf"

3 (изменено: Rumata, 2013-08-19 20:27:37)

Re: CMD/BAT/BASH: jpeg -> pdf

alexii
Спасибо. Вот и второе решение. Буквально сразу как увидел Ваше сообщение, проверил существование ImageMagick. У меня есть.

И есть выбор:
1. мое предложение - файл меньшего размера, но есть скроллинг (страница выглядит как лист формата А4 с картинкой по середине)
2. ваше предложение - файл чуть больше, но страница содержит только одну картинку.

( 2 * b ) || ! ( 2 * b )

4

Re: CMD/BAT/BASH: jpeg -> pdf

NConvert тоже справляется.
Из бесплатных есть ещё такая JPEGtoPDF (увы, на VB.NET).
Ещё из консольных знаю 3 платника, напичканных кучей полезных функций. Если надо, дам ссылки.

5

Re: CMD/BAT/BASH: jpeg -> pdf

Flasher, я изначально смотрел как раз в сторону NConvert, но он бесплатен только «for non-commercial» пользования, а автору вопроса предстояло пользовать сие в своей конторе.

6 (изменено: Flasher, 2013-08-20 01:07:11)

Re: CMD/BAT/BASH: jpeg -> pdf

alexii
У меня вопрос: а мы говорим не о мультистраничном склеивании картинок в один PDF?
Если только о одностраничниках, то вариантов масса: демоверсии консольных программ (у кот. главное ограничение - число картинок в  одном pdf без штампа), jpegtopdf и именитая IrfanView (правда она тоже для некоммерческого использования).

7

Re: CMD/BAT/BASH: jpeg -> pdf

У меня вопрос: а мы говорим не о мультистраничном склеивании картинок в один PDF?

Я сначала так и решил, и даже полез было разбираться с Ghostscript, но потом понял, что речь об этом не идёт. Но если здесь будет — тем лучше.

8

Re: CMD/BAT/BASH: jpeg -> pdf

Flasher
Вопрос стоит именно в конвертировании одна картинка - один документ.

Если есть необходимость склеить несколько картинок в один файл, то можно использовать тот же ImageMagick:


convert -adjoin -format pdf file1.jpg file2.jpg output.pdf
( 2 * b ) || ! ( 2 * b )

9

Re: CMD/BAT/BASH: jpeg -> pdf

Rumata
Тогда лучше используйте jpegtopdf без Cygwin-ов всяких.
Как склеивать картинки в PDF (и не только) разными средствами, включая ImageMagick, я прекрасно знаю, и в этом смысле у меня давно всё налажено. Я лишь даю варианты на выбор.

10

Re: CMD/BAT/BASH: jpeg -> pdf

Flasher
Спасибо. Я ее уже протестировал. Программа хорошая. Буду использовать оба варианта - и jpegtopdf и convert, в зависимости от ситуации.

( 2 * b ) || ! ( 2 * b )

11 (изменено: Rumata, 2013-08-29 18:28:54)

Re: CMD/BAT/BASH: jpeg -> pdf

А вот эта программа просто прелесть. Вначале чуть-чуть перевода вступительной части. Описание аргументов поместил под спойлер, без перевода.

MiniCap

MiniCap это маленькое приложение для захвата экрана с хорошей поддержкой командной строки, включая возможность запускать (и затем завершать) приложения, захватывать окна по дескриптору, ID и имени процесса или интерактивно.

MiniCap обладает удобным интерактивным режимом захвата, но где действительно ярко себя проявляет MiniCap это его использование в качестве не интерактивной программы из командной строки.

Прелесть в том, что ее работу можно легко контролировать. Радует количество поддерживаемых форматов: .jpg, .gif, .pdf, .png, .bmp, .tiff. То есть при желании можно сразу создать PDF без манипуляций с промежуточными картинками типа JPG.

Для себя я решил использовать так:


:: После сохранения изображения завершиться
:: Подождать 3 секунды перед захватом
:: Захватить активное окно
:: Сохранить в файл с заданным именем
MiniCap -exit -sleep 3 -captureactivewin -save "%~1"
+ Опции командной строки

If run on the commandline without any arguments, MiniCap starts up in interactive capture mode, where you can select the object on screen to capture and then save the file with a filename and format of your choice.

However, the more common use for MiniCap is in non-interactive commandline mode. You can use the following commandline arguments for non-interactive capture:

-save "OUTPUTFILENAME"
Tells MiniCap to automatically save the captured image using the specified filename, including path, and extension which should include the image format extension of your choice (.jpg, .gif, .pdf, .png, .bmp, .tiff).

You can use certain fields which will be replaced:
$appdir$ - application directory (useful if you want to save snapshot in same directory)
$appname$ - application exe name (without path)
$nicename$ - nice name of application exe (taken from exe resource)
$windowtitle$ - window caption
$uniquenum$ - adds unique number to filename to avoid overwriting existing files (number only added when needed to avoid existing file)
$uniquenum0$ - adds unique number to filename to avoid overwriting existing files (number ALWAYS added)
$datetime$ , $date$ , $time$ - local date/time
$dt:%DATEFORMATSTRING$ - where DATEFORMATSTRING is made up from the following:

%a Abbreviated weekday name
%A Full weekday name
%b Abbreviated month name
%B Full month name
%c Date and time representation appropriate for locale
%d Day of month as decimal number (01 – 31)
%H Hour in 24-hour format (00 – 23)
%I Hour in 12-hour format (01 – 12)
%j Day of year as decimal number (001 – 366)
%m Month as decimal number (01 – 12)
%M Minute as decimal number (00 – 59)
%p Current locale's A.M./P.M. indicator for 12-hour clock
%S Second as decimal number (00 – 59)
%U Week of year as decimal number, with Sunday as first day of week (00 – 53)
%w Weekday as decimal number (0 – 6; Sunday is 0)
%W Week of year as decimal number, with Monday as first day of week (00 – 53)
%x Date representation for current locale
%X Time representation for current locale
%y Year without century, as decimal number (00 – 99)
%Y Year with century, as decimal number
%z Time-zone name
%Z Time-zone abbreviation

-closeapp
Tells the app that is run to close after screenshot is taken
If you don't specify -closeapp or -killapp then the app will be left running after the app is launched

-killapp
Closes app harshly if it won't close by normal request

-sleep #
Sleep # seconds before engaging capture

-capturescreeen
Capture current screen

-capturedesktop
Capture entire desktop workspace (all multimonitors if more than one exists)

-capturerunapp
Automatically capture the application specified by a -run argument

-capturehwnd #
Automatically capture the window with the specified handle number (specified in decimal)

-capturepid #
Automatically capture the main window of the application with the specified process id (specified in decimal)

-captureregion left top right bottom
Capture screeen region specified

-captureregselect
Interactive capture of region (traditional style mode -- locked to current screen of multimonitor)

-captureredregselect
Interactive capture of region (red box mode)

-captureobjselect
Interactive capture of object (red box mode)

-captureappbyname "filename.exe"
Find the window of the running exe specified and capture it (specify filename with extension but no path)

-captureactivewin
Capture last active window

-exit
Exit minicap after the screenshot is saved
If you don't specify this then MiniCap will remain open after the capture.

-scrollcap
Use scrolling window capture more

-setfore
Set window to be captured to foreground before capturing

-client
Captures client area of the window, useful when capturing windows which have no borders/titlebar

-run "APPNAME" [args+]
Runs a specific application specified before capturing.
All arguments after appname are passed on the commandline to the app, so -run needs to be the last argument you specify

-runcap "APPNAME" [args+]
Same as calling with -run and automatically adds the following arguments for easy use:
"-closeapp -exit -sleep 3 -captureapp"
Like -run, this needs to be the LAST arguments you specify

-postrun "COMMANDLINEWITHARGS"
runs a program after the image is saved (use $file$ to replace saved image filename in commandline)

-compress #
Set compression quality from 1 to 10 (10 is highest quality and biggest image); default to 8

-clipimage
Copy the image to clipboard after capture

-clipimagepath
Copy the saved image filename (full path) to clipboard after capture

-bordershadow
Add a nice border and shadow to image

-promptsave
Asks user for filename to save immediately after a capture.
If combined with a filename specified using -save "FILENAME" then you will be prompted to save as with the filename pre-filled out.

-resizexp PERCENTAGE
resize x dimension to PERCENTAGE% of its original value (y will be scaled to preserve ratio if no y resize value specified)

-resizeyp PERCENTAGE
resize y dimension to PERCENTAGE% of its original value (x will be scaled to preserve ratio if no x resize value specified)

-resizex WIDTH
resize x dimension to exactly WIDTH pixels (y will be scaled to preserve ratio if no y resize value specified)

-resizey HEIGHT
resize y dimension to exactly HEIGHT pixels (y will be scaled to preserve ratio if no y resize value specified)

-print
print the captured image

-printpreview
show a print preview before printing and allow adjustment of margins, etc.

-setprinter PRINTERNAME
sets a specific printer for printing (to get a list invoke -setprinter list); you can use the full name or a substring

-convert CONVERTMODE
CONVERTMODE is from:
bwo = Black+White (ordered)
bwf = Black+White (floydSteinberg method)
bwt = Black+White (local threshold)
bwt1 = Black+White (global threshold of 128)
bwt2 = Black+White (global threshold of avg pixel)
btw3 = Black+White (global threshold set by entropy)
gray = Grayscale

-noaero
disables the new aero capture mode even on vista/win7 machines

-aeroborder THRESHOLD
THRESHOLD should be an integer from 0 to 255
if set to 0 then no automatic shadow removal/border trimming will take place, and a larger image with the aero shadow will be captured.
a higher value, like 200, will attempt to clean up the borders and result in small image dimensions by removing bordering pixels with alpha values smaller than that specified.

-aerocolor COLORCOMPONENTVALUE
COLORCOMPONENTVALUE should be an integer from 0 to 255
if you specify 0 you will get a black background when flattening (see below), if 255 then a white background when flattening

-aeroflatten
flattens the area inside the border so that the image has only 2 levels of transparency -- purely transparent outside the border (see option above), and purely opaque inside the border region. the -aerocolor parameter specifies the background color to merge transparency with when flattening.

-dpi VALUE
sets the DPI value in the image properties of the saved image (useful when importing images into MS word, printing, etc.



Example:
MiniCap.exe -save "C:\screen_$appname$$uniquenum$_$date$.jpg" -closeapp -exit -sleep 4 -capturerunapp -run "C:\Program Files\Macromedia\FlashPlayer.exe" "C:\MyMovie.swf"

MiniCap.exe -capturerunapp -exit -save "D:\desktop.png" -sleep 5 -closeapp -exit -run "C:\WINDOWS\system32\notepad.exe" "C:\WINDOWS\test.txt"


-save "E:\test.jpg" -runcap "C:\WINDOWS\system32\notepad.exe" "C:\WINDOWS\test.txt"

( 2 * b ) || ! ( 2 * b )

12

Re: CMD/BAT/BASH: jpeg -> pdf

ghoctscript умеет, только нужно написать верный ps файл

Я конечно далек от мысли... (с)