ghostscript unexpectedly returned exit value 1 - ghostscript

Calling ghostscript from a Perl script I get this error:
"/usr/local/bin/gs" unexpectedly returned exit value 1
In $! this string can be found: "Inappropriate ioctl for device" - I am not sure, if this is related to the gs error.
Searching for the documentation of ghostscript, I found this page:
http://www.ghostscript.com/doc/current/API.htm#return_codes
Unfortunatley 1 is not listed there.
Any idea what's going wrong here?
EDIT: After changing the code a bit, I realized that the file given to gs was a JPEG and not a PDF. That's probably the reason but does not explain the exit-code of 1.
For the reference here is the Perl-code which throws the above error message:
my ($stdout, $stderr, $exit) = capture {
my $cmd = '/usr/local/bin/gs';
my #args = (qw( -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=- )) ;
push #args, $tmp_fn;
use IPC::System::Simple qw(system);
system($cmd, #args);
};
die "ERROR compressing pdf: $stderr" if $stderr;

Related

update CFBundleShortVersionString with script gives error in Xcode 11

I am trying to update with this script my extension app which is inside the main app.
In general when i commit with svn, the version of my main app update, now i need to update the extension version also.
I am trying to use the following script but seems it gives error. any idea?
this is the example:
version_number=$1
build_number=$2
#
echo "version_number is $version_number"
echo "build_number is $build_number"
pruvitInfoPlist="ServiceExtension/Info.plist"
/usr/libexec/PlistBuddy -c "Set CFBundleShortVersionString $version_number" $pruvitInfoPlis
The Error:
> Build/file.rb:41: syntax error, unexpected unary-, expecting do or '{'
> or '(' /usr/libexec/PlistBuddy -c "Set CFBundleShortVersionSt...
> ^ Build/file.rb:41: syntax error, unexpected tGVAR, expecting end-of-input ...ersion_number" $pruvitInfoPlist ...
> ^~~~~~~~~~~~~~~~ Command PhaseScriptExecution failed with a nonzero
> exit code
I am going to Answer my question here maybe in can help someone else.
I resolved the issue with script in extension.
plistFile = "#{ENV['BUILT_PRODUCTS_DIR']}/#{ENV['INFOPLIST_PATH']}"
`/usr/bin/plutil -convert xml1 "#{plistFile}"`
unless pl = Plist::parse_xml(plistFile)
puts "Could parse #{plistFile}"
exit
end
freshPlFile = "#{ENV['SOURCE_ROOT']}/ServiceExtension/Info.plist"
`/usr/bin/plutil -convert xml1 "#{freshPlFile}"`
unless freshPl = Plist::parse_xml(freshPlFile)
puts "Could parse #{freshPlFile}"
exit
end
version = pl["CFBundleShortVersionString"].gsub(/ \([a-f0-9 \/:]*\)/, '')
# keep only the major and minor version number and add the revision
version.gsub!(/([^\.]*)\.([^\.]*).*/, "\\1.\\2.#{revision}");
pl["CFBundleShortVersionString"] = version
pl["CFBundleVersion"] = Time.now.utc.strftime("%Y%m%d%H")
pl.save_plist(plistFile)
`/usr/bin/plutil -convert binary1 #{plistFile}`
puts "#{plistFile}:"
puts "CFBundleVersion = #{pl["CFBundleVersion"]}"
puts "CFBundleShortVersionString = #{pl["CFBundleShortVersionString"]}"
every time i commit it update my extension and my main app. you need to add this script also in main app.

ruby rmagick FailedToExecuteCommand `"gs"

I run in loop converting of pdf scans (base64 data) to jpg images with rmagick with this code
Magick::Image.read_inline(data) do
self.quality = 100
self.density = '150'
self.interlace = Magick::NoInterlace
end.each_with_index do |img, i|
img.write(rpvs_dir+"temp-#{i}.jpg")
end
it looks it works fine but after 10-15 documents it starts throwing this error
FailedToExecuteCommand `"gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE
-dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pngalpha" -dTextAlphaBits=4 -dGraphicsAlphaBits=4
"-r150x150" "-sOutputFile=/tmp/magick-17139yIssgZl8Dg7O%d"
"-f/tmp/magick-17139VEtM2IeDiPfF" "-f/tmp/magick-17139ANIid4R9Yoov"'
(-1) # error/delegate.c/ExternalDelegateCommand/461
then some documents are fine and it starts again.
is it related to memory or what might be the problem? from error message I cannot find out what might be wrong

Is it possible to use EPS file (created with eps2write) in EndPage procedure?

For testing purposes, let's draw some meaningless rectangles:
gswin32c -q -o f.pdf -sDEVICE=pdfwrite -c "<</PageSize[595 842]>>setpagedevice 0 0 595 842 rectfill showpage"
+
gswin32c -q -o f.eps -sDEVICE=eps2write -f f.pdf
And ps.ps file:
<<
/EndPage {
exch pop
2 ne dup {
1 dict begin
/showpage {} def
(f.eps) run
end
} if
}
>> setpagedevice
And then
gswin32c -q -o out.pdf -sDEVICE=pdfwrite -f ps.ps -f f.pdf
produces an error:
%%[ Error handled by opdfread.ps : GPL Ghostscript 9.15: Unrecoverable
error, exit code 1 Unrecoverable error: typecheck in if Operand stack:
typecheck ebuf false false --nostringval--
On the other hand, if I create EPS with another tool, e.g. xpdf's pdftops:
pdftops -eps f.pdf f.eps
... then EPS can be placed as e.g. watermark or logo with above command:
gswin32c -q -o out.pdf -sDEVICE=pdfwrite -f ps.ps -f f.pdf
So the question is, is it possible to use Ghostscript's eps2write for the purpose, maybe I'm missing something.
I tried to bracket (f.eps) run with calls to BeginEPSF and EndEPSF as defined in Adobe's EPSF Format Specification, but it didn't help. And after decoding prologue which eps2write creates (which, itself, gives same error if run from EndPage), it looks to me that it violates section on Illegal and Restricted Operators of mentioned Specification.
Edit:
I think there's an issue with the Immediately Evaluated Names if code is run from EndPage. In prologue, which eps2write creates, there's a fragment not very far from the beginning:
//SetPageSize{
//RotatePages//FitPages or//CenterPages or{
mark(/RotatePages, /FitPages and CenterPages are not allowed with /SetPageSize)//error exec
}if
}
{
//FitPages//CenterPages and{
mark(CenterPages is not allowed with /FitPages)//error exec
}if
}
ifelse
If I frame it like this:
SetPageSize ==
//SetPageSize ==
{
//SetPageSize{
//RotatePages//FitPages or//CenterPages or{
mark(/RotatePages, /FitPages and CenterPages are not allowed with /SetPageSize)//error exec
}if
}
{
//FitPages//CenterPages and{
mark(CenterPages is not allowed with /FitPages)//error exec
}if
}
ifelse
} stopped { (***\n) print } if
And modify ps.ps slightly:
<<
/EndPage {
exch pop
2 ne dup {
1 dict begin
/showpage {} def
(prologue.ps) run
end
} if
}
>> setpagedevice
Then this command:
gswin32c -q -o out.pdf -sDEVICE=pdfwrite -f ps.ps -f f.pdf
...gives this output:
false
/SetPageSize
***
%%[ Error handled by opdfread.ps : GPL Ghostscript 9.14: Unrecoverable error, exit code 1
I.e. it fails in above fragment (and for obvious reason, I think) and then fails somewhere else further down within prologue.ps.
OK so I did something similar to your expereience. I started with a simple PostScript file (testeps.ps):
%!
0 1 0 setrgbcolor
0 0 100 100 rectfill
showpage
I then ran that through Ghostscript using the eps2write device:
./gs -sDEVICE=eps2write -sOutputFile=out.eps -dCompressPages=false testeps.ps
I then constructed another test file (test.ps):
%!
<<
/EndPage {
exch pop
2 ne dup {
1 dict begin
/showpage {} def
(/temp/out.eps) run
end
} if
}
>> setpagedevice
1 0 0 setrgbcolor
0 100 100 100 rectfill
showpage
and ran that through GS:
./gs test.ps
The file ran to completion, and contained appropriately coloured rectangles at the correct positions on the page.
Its possible this is something which has been fixed (you don't say what version of Ghostscript you are using). The next release (9.16) is due very shortly, or you can build iot yourself from source, I'd suggest you try it when its available.

How to get the real line number of a failing Bash command?

In the process of coming up with a way to catch errors in my Bash scripts, I've been experimenting with "set -e", "set -E", and the "trap" command. In the process, I've discovered some strange behavior in how $LINENO is evaluated in the context of functions. First, here's a stripped down version of how I'm trying to log errors:
#!/bin/bash
set -E
trap 'echo Failed on line: $LINENO at command: $BASH_COMMAND && exit $?' ERR
Now, the behavior is different based on where the failure occurs. For example, if I follow the above with:
echo "Should fail at: $((LINENO + 1))"
false
I get the following output:
Should fail at: 6
Failed on line: 6 at command: false
Everything is as expected. Line 6 is the line containing the single command "false". But if I wrap up my failing command in a function and call it like this:
function failure {
echo "Should fail at $((LINENO + 1))"
false
}
failure
Then I get the following output:
Should fail at 7
Failed on line: 5 at command: false
As you can see, $BASH_COMMAND contains the correct failing command: "false", but $LINENO is reporting the first line of the "failure" function definition as the current command. That makes no sense to me. Is there a way to get the line number of the line referenced in $BASH_COMMAND?
It's possible this behavior is specific to older versions of Bash. I'm stuck on 3.2.51 for the time being. If the behavior has changed in later releases, it would still be nice to know if there's a workaround to get the value I want on 3.2.51.
EDIT: I'm afraid some people are confused because I broke up my example into chunks. Let me try to clarify what I have, what I'm getting, and what I want.
This is my script:
#!/bin/bash
set -E
function handle_error {
local retval=$?
local line=$1
echo "Failed at $line: $BASH_COMMAND"
exit $retval
}
trap 'handle_error $LINENO' ERR
function fail {
echo "I expect the next line to be the failing line: $((LINENO + 1))"
command_that_fails
}
fail
Now, what I expect is the following output:
I expect the next line to be the failing line: 14
Failed at 14: command_that_fails
Now, what I get is the following output:
I expect the next line to be the failing line: 14
Failed at 12: command_that_fails
BUT line 12 is not command_that_fails. Line 12 is function fail {, which is somewhat less helpful. I have also examined the ${BASH_LINENO[#]} array, and it does not have an entry for line 14.
For bash releases prior to 4.1, a special level of awful, hacky, performance-killing hell is needed to work around an issue wherein, on errors, the system jumps back to the function definition point before invoking an error handler.
#!/bin/bash
set -E
set -o functrace
function handle_error {
local retval=$?
local line=${last_lineno:-$1}
echo "Failed at $line: $BASH_COMMAND"
echo "Trace: " "$#"
exit $retval
}
if (( ${BASH_VERSION%%.*} <= 3 )) || [[ ${BASH_VERSION%.*} = 4.0 ]]; then
trap '[[ $FUNCNAME = handle_error ]] || { last_lineno=$real_lineno; real_lineno=$LINENO; }' DEBUG
fi
trap 'handle_error $LINENO ${BASH_LINENO[#]}' ERR
fail() {
echo "I expect the next line to be the failing line: $((LINENO + 1))"
command_that_fails
}
fail
BASH_LINENO is an array. You can refer to different values in it: ${BASH_LINENO[1]}, ${BASH_LINENO[2]}, etc. to back up the stack. (Positions in this array line up with those in the BASH_SOURCE array, if you want to get fancy and actually print a stack trace).
Even better, though, you can just inject the correct line number in your trap:
failure() {
local lineno=$1
echo "Failed at $lineno"
}
trap 'failure ${LINENO}' ERR
You might also find my prior answer at https://stackoverflow.com/a/185900/14122 (with a more complete error-handling example) interesting.
That behaviour is very reasonable.
The whole picture of the call stack provides comprehensive information whenever an error occurs. Your example had demonstrated a good error message; you could see where the an error actually occurred and which line triggered the function, etc.
If the interpreter/compiler can't precisely indicate where the error actually occurs, you could be more easily confused.

Count PDF pages from stdin with Ghostscript (PostScript)

Well I found on stackoverflow how to count pages of PDF file using Ghostscript by executing the following command on a shell
gs -q -dNODISPLAY -c "($PATH_TO_PDF) (r) file runpdfbegin pdfpagecount = quit"')
I would like to get the pdf from stdin.
I'll played a little bit around, but with no success.
My approach was:
gs -q -dNODISPLAY - -c "(%stdin) (r) file runpdfbegin pdfpagecount = quit"')
I get no output.
Any hints or suggestions?
You cannot work with PDF files from stdin, as the PDF format makes it more or less essential to be able to have random access to all parts of the file.
In the cases where Ghostscript reads a PDF file from stdin it first copies it to a local file then works on that, so it isn't working from stdin anyway.
In short, this can't be done.
This works:
gs -q -dNODISPLAY -c "($PATH_TO_PDF) (r) file runpdfbegin pdfpagecount = quit";
I think the problem with your attempt to use
gs -q -dNODISPLAY -c "($PATH_TO_PDF) (r) file runpdfbegin pdfpagecount = quit"')
was the unmatched closing bracket after QUIT
It can be done.
String ars = "-q -dNODISPLAY -dNOPAUSE -sDEVICE=tiffg3 -r150.4 -o" + outputImagesPath + "%d.tiff -sPAPERSIZE=a4 " + inputPDFFile + " -c quit";
Process proc = new Process();
proc.StartInfo.FileName = ghostScriptPath;
proc.StartInfo.Arguments = ars;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();
//Raise Your Complete Job Event Here And User Directory.GetFiles("..").Count

Resources