Ghostscript ps2pdf not Working Correctly from MATLAB - matlab

I have a .tex file I am attempting to write from a MATLAB environment (2017b) using first latex, then dvips, and finally ps2pdf to create the PDF file. The PDF file is properly created when I run it through TeXWorks, but sends an error from ps2pdf when I try to run it through. I'm not entirely sure what's wrong with the way I send it to the command line. Here is the script I am attempting to run.
set(groot, 'defaultAxesTickLabelInterpreter','latex');
set(groot, 'defaultLegendInterpreter','latex');
set(0,'defaultTextInterpreter','latex');
addpath('C:\Program Files (x86)\MiKTeX\miktex\bin\x64')
exampledir='\\our\server\';
examplefilename='test';
texdoc=fullfile(exampledir,strcat(examplefilename,'.tex'));
auxdoc=fullfile(exampledir,strcat(examplefilename,'.aux'));
logdoc=fullfile(exampledir,strcat(examplefilename,'.log'));
dvidoc=fullfile(exampledir,strcat(examplefilename,'.dvi'));
psdoc=fullfile(exampledir,strcat(examplefilename,'.ps'));
pdfdoc=fullfile(exampledir,strcat(examplefilename,'.pdf'));
fileID = fopen(texdoc,'w');
textext=['\documentclass[twoside]{article} %Two-sided document. Required for fancyhf left and right page numbering scheme current.' newline ...
'\usepackage{graphicx}' newline ...
newline ...
'\usepackage{fancyhdr} %Use the package fancy header/footer' newline ...
newline ...
'\usepackage[letterpaper,margin=0.5in,bottom=0.75in,top=0.7in]{geometry} %Ensure the paper is letterpaper.' newline ...
'\usepackage{grffile}' newline ...
'\usepackage{caption}' newline ...
'\usepackage{float} %Float used to position graphics.' newline ...
'\usepackage{lastpage209} %For last page' newline ...
newline ...
'\DeclareGraphicsExtensions{.PDF,.jpg} %Notify LaTeX what type of graphics extensions to expect.' newline ...
newline ...
'\renewcommand{\headrulewidth}{0pt} % remove the header rule' newline ...
newline ...
'\fancyhf{} % clear all header and footers' newline ...
newline ...
'\pagestyle{fancy} %Use the fancy pagestyle, which will include the fancy header and footer options we defined above.' newline ...
newline ...
'\setlength\headheight{38pt} ' newline ...
newline ...
'\fancyhead[L]{{Page \thepage} of \pageref{LastPage}} %Left side on even pages; right side on odd pages.' newline ...
'\fancyhead[R]{\includegraphics[trim={0.3in 0.26in 0.05in 0.26in},clip,width=0.4in]{{\\our\server\mypicture}}}' newline ...
newline ...
'\begin{document} %This will be the actual document and what goes into it.' newline ...
newline ...
'\begin{figure}[h] %Make a figure...' newline ...
newline ...
' \includegraphics[trim={0.25in 0 0 0},clip,width=7.5in]{{\\our\server\mypicture}}' newline ...
newline ...
' \captionsetup{labelformat=empty}' newline ...
newline ...
'\end{figure}' newline ...
newline ...
'\end{document}'];
fprintf(fileID,'%s',textext);
fclose(fileID);
% latex dvips ps2pdf
% text.tex -------> text.dvi -------> text.ps --------> text.pdf
[~,cmdoutlatex] = system(['latex.exe -interaction=nonstopmode -output-directory ' exampledir '\ ' texdoc]);
if contains(cmdoutlatex,'Sorry, but latex.exe did not succeed.')
%Do some kind of check and fix things.
end
[~,cmdoutdvips] = system(['dvips.exe -q* -o ' psdoc ' ' dvidoc]);
if contains(cmdoutdvips,'!')
%Do some kind of check and fix things.
error(['Error: ' cmdoutdvips])
end
[~,cmdoutps2pdf] = system(['ps2pdf ' psdoc ' ' pdfdoc ' -sDEVICE=pdfwrite']);
if contains(cmdoutps2pdf,'Error','IgnoreCase',true)
%Do some kind of check and fix things.
error(cmdoutps2pdf)
end

Per #Cris Luengo's suggestion of moving to pdflatex rather than using latex/dvips/ps2pdf commands, this worked. Here is the sample code of what worked for a system command.
[~,pdflatexout] = system(['pdflatex.exe -output-directory ' strrep(exampledir,'\','/') ' ' texdoc]);
%Check for errors.
if contains(pdflatexout,'Sorry, but pdflatex.exe did not succeed.') || ...
contains(pdflatexout,'error','IgnoreCase',true)
%Deliver the error code.
error(pdflatexout)
end
I placed this after fclose(fileID) in the original code and deleted all that had originally come after that line.

Related

Write urdu in notepad file using matlab

I have a Urdu Optical character Recognition. When I convert my image text to Unicode and write it in notepad file it shows like "ÌÇ Ûã ˜Ç äíÇ ÝÑ " not in urdu language. Here is my code
disp(native2unicode(rst))
f = fopen('temp.txt', 'w', 'native', 'UTF-8');
s = char(native2unicode(rst));
fprintf(f, ' %s.\r\n', s);
fclose(f);
The following code runs fine on my system. Maybe the added 'UTF-8' parameter helped?
rst='اردو‎';
disp(native2unicode(rst,'UTF-8'))
s = char(native2unicode(rst,'UTF-8'));
f = fopen('temp.txt', 'w', 'native', 'UTF-8');
fprintf(f, ' %s.\r\n', s);
fclose(f);

How to replace several lines but not the last

I need to remove lines from word "WORDA" to the last "}" before WORDB.
But there are other "}" before. So SED missed the selection.
...
WORDA
{
blah
{
blahblah
...
blahblahblah
}
}
WORDB 0
...
So I'm trying to replace from "WORDA" to "WORDB" with "WORDB" but I lose the "0" at the end... The result is not inserted... All the last line is replaced.
(Of course, this "0" value can be any other number.)
sed.exe -i /WORDA/,/WORDB/c\WORDB\ file
result
...
WORDB
...
but I need:
...
WORDB 0
...
Any idea?
Crude but effective:
sed '/WORDA/,/WORDB/{/WORDB/!d;}' filename

Jekyll's is removing static file during cleanup

I want to include a gnuplot code inside a markdown page and have Jekyll compile the graph when I save it. The graph image is being saved. But it is removed during jekyll's cleanup. The closest that I have found toward a solution is at Copying generated files from a Jekyll plugin to a site resource folder. However, I don't undersand the overall flow of Jekyll and how I keep static files from being removed. I have added site.static_files << Jekyll::StaticFile.new(site, site.source, path, filename) with no results.
If I create a dummy file outside of the _site folder, Jekyll will keep my file safe inside the _site file. I would rather not have to create that dummy file.
Here is code for my plugin. Any help will be awesome.
class RenderGNUplot < Liquid::Block
def initialize(tag_name, markup, tokens)
super
#markup = markup
#attributes = {}
markup.scan(Liquid::TagAttributes) do |key, value| #attributes[key.to_sym] = value end
end
def gnuplot(commands)
IO.popen("gnuplot", "w") { |io| io.puts commands }
end
def render(context)
site = context.registers[:site]
#file = ""
commands = super
if ( commands =~ /set output "(.*)"/ )
setfile_regex = Regexp.new(/set output "((.*))"/)
filepath = commands[setfile_regex, 1]
#file = File.basename filepath
commands = commands.sub!(commands[setfile_regex], 'set output "_site/media/' + #file +'"' )
p commands
end
gnuplot(commands)
site.static_files << Jekyll::StaticFile.new(site, site.source, "_site/media/", "#{#file}")
# site.static_files << Jekyll::StaticSitemapFile.new(site, site.dest, '/', 'sitemap.xml')
"<object id='' type='image/svg+xml' data='#{site.baseurl}/media/{#file}'>Your browser does not support SVG</object>"
end
end
Liquid::Template.register_tag('test', RenderGNUplot)
And Markdown page
---
layout: post
title: "Thin Server"
date: 2015-04-28 10:42:56
categories: thin
---
{% test location: Test%}
set terminal svg size 600,400 dynamic enhanced fname 'arial' fsize 10 #mousing jsdir 'http://localhost:4000/media/' name "histograms_1" butt dashlength 1.0
set output "media/curves.svg"
set key inside left top vertical Right noreverse enhanced autotitle box lt black linewidth 1.000 dashtype solid
set samples 50, 50
set title "Simple Plots"
set title font ",20" norotate
plot [-10:10] sin(x),atan(x),cos(atan(x))
{% endtest%}
This is the exact code that I am using. It only has the Liquid block and jekyll StaticFile
class GNUplotFile < Jekyll::StaticFile
def write(dest)
puts "WRITE---->>>>>>>>>>>"
#File.write('_site/media/BTTTTT.svg', DateTime.now)
gnuplot(#commands)
# do nothing
end
def gnuplot(commands)
IO.popen("gnuplot", "w") { |io| io.puts commands }
end
def givemethecommands(commands)
#commands = commands
end
end
class RenderGNUplot < Liquid::Block
def initialize(tag_name, markup, tokens)
super
#markup = markup
#attributes = {}
markup.scan(Liquid::TagAttributes) do |key, value| #attributes[key.to_sym] = value end
end
def render(context)
site = context.registers[:site]
#file = ""
commands = super
if ( commands =~ /set output "(.*)"/ )
setfile_regex = Regexp.new(/set output "((.*))"/)
filepath = commands[setfile_regex, 1]
#file = File.basename filepath
commands = commands.sub!(commands[setfile_regex], 'set output "_site/media/' + #file +'"' )
#p commands
end
gnuplot = GNUplotFile.new(site, site.source, "_site/media/", "#{#file}")
gnuplot.givemethecommands commands
site.static_files << gnuplot
# site.static_files << Jekyll::StaticFile.new(site, site.dest, '/', 'sitemap.xml')
"<object id='' type='image/svg+xml' data='#{site.baseurl}/media/#{#file}'>Your browser does not support SVG</object>"
end
end
Liquid::Template.register_tag('test', RenderGNUplot)

ANTLR: loop did not match anything at input

sorry for my english! I have problem, faced here with such a problem, give the decision:
line 1:0 required (...)+ loop did not match anything at input < E O F
>
This my file, calc.g
grammar calc;
options {
language = Java;
}
rule: statement+;
statement
: expr NEWLINE
| ID '=' expr NEWLINE
| NEWLINE
;
NEWLINE : '\r'? '\n'
;
expr
: multExpression ('+' multExpression |'-' multExpression)*
;
multExpression
: a1=atom ('*' a2=atom | '/' a2=atom)*
;
atom
: ID
| INT
| '(' expr ')'
;
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
;
INT : ('1'..'9') ('0'..'9')*
;
this is my main:
ANTLRReaderStream input = new ANTLRReaderStream();
calcLexer lexer = new calcLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
calcParser parser = new calcParser(tokens);
parser.rule();
It looks like your input is empty: the parser immediately encounters the EOF (end-of-file) where it expects at least one statement.
Try something like this:
ANTLRStringStream input = new ANTLRStringStream("2*42\n");
calcLexer lexer = new calcLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
calcParser parser = new calcParser(tokens);
parser.rule();
As 280Z28 mentioned in the comment beneath my answer, you should probably force the parser to consume the entire input by adding EOF at the end of your parser's entry point:
rule: statement+ EOF;
and if you want to allow an empty string to be valid input too, change the + to a *;
rule: statement* EOF;
I didn't test it but think you have to add the default EOF token to your grammar:
rule: statement+ EOF!;
Your parser seems to recognize the whole input but at the end there is an EOF but you did not add the corresponding rule to your grammar.

Ghostscript error converting multi-page PS to multi-page PDF using pdfwrite

I'm using Matlab to output a multi-page PS file:
print(figure, '-dpsc2', fullfile(folder, [file '.ps']), '-r600', '-append')
and then using Matlab to invoke Ghostscript to convert the resulting PS file to a PDF:
system(['"' gsPath '" -sDEVICE=pdfwrite \
-dDEVICEWIDTHPOINTS=' num2str(int32(width*72)) ' \
-dDEVICEHEIGHTPOINTS=' num2str(int32(height*72)) ' \
-dPDFFitPage \
-o "' fullfile(folder, [file '.pdf']) '" "' fullfile(folder, [file '.ps']) '"']);
which is just a really hard-to-read way of writing something along the lines of
gswin64c -sDEVICE=pdfwrite ^
-dDEVICEWIDTHPOINTS=100 ^
-dDEVICEHEIGHTPOINTS=100 ^
-dPDFFitPage ^
-o "C:\folder\output.pdf" "C:\folder\input.ps"
where I've put in example values for device dimensions and input/output paths. When I use this code to print a single figure (one page) to PDF, everything works perfectly. However, when printing multiple figures (multiple pages) to PDF, Ghostscript throws an error:
GPL Ghostscript 9.06 (2012-08-08)
Copyright (C) 2012 Artifex Software, Inc. All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
**** Unable to open the initial device, quitting.
Now, if I remove the -dDEVICEWIDTHPOINTS=100 -dDEVICEHEIGHTPOINTS=100 part of my Ghostscript command and again attempt to print multiple figures to a PDF, it works fine (except for the page size being different than what I want).
GPL Ghostscript 9.06 (2012-08-08)
Copyright (C) 2012 Artifex Software, Inc. All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Loading NimbusSanL-Regu font from %rom%Resource/Font/NimbusSanL-Regu... 4032872 2490784 2311720 1014184 2 done.
Has anyone else run into a similar problem and found a workaround for this issue? One of the keys here is that I need to be able to control the page size of the PDF produced. Thanks!
Below is an example that should run fine. First we create a multi-page PS file:
fname = 'test';
if exist([fname '.ps'], 'file'), delete([fname '.ps']); end
hfig = figure;
for i=1:10
plot(cumsum(rand(100,1)-0.5))
drawnow
print(hfig, '-dpsc2', '-append', [fname '.ps'])
end
close(hfig)
Next we convert it to PDF using Ghostscript, and properly crop the figures:
gs_path = 'C:\Program Files\gs\gs9.07\bin\gswin64c.exe';
gs_opts = '-dBATCH -dNOPAUSE -q';
% ps2pdf
cmd = sprintf('"%s" %s -sDEVICE=pdfwrite -dPDFFitPage -o %s %s', ...
gs_path, gs_opts, [fname '.pdf'], [fname '.ps']);
disp(cmd); system(cmd);
% get bbox
cmd = sprintf('"%s" %s -sDEVICE=bbox %s', ...
gs_path, gs_opts, [fname '.pdf']);
disp(cmd); [~,out] = system(cmd);
out = textscan(out, '%s', 'Delimiter','');
bbox = regexp(out{1}, '^%%BoundingBox: (\d+) (\d+) (\d+) (\d+)','tokens','once');
bbox = str2double(vertcat(bbox{:}));
bbox = [min(bbox(:,1:2)) max(bbox(:,3:4))];
% crop to bounding box
cmd = sprintf(['"%s" %s -o %s -sDEVICE=pdfwrite' ...
' -dDEVICEWIDTHPOINTS=%d -dDEVICEHEIGHTPOINTS=%d -dFIXEDMEDIA' ...
' -c "<</PageOffset [-%d -%d]>> setpagedevice" -f %s'], ...
gs_path, gs_opts, [fname '_cropped.pdf'], ...
bbox(3)-bbox(1), bbox(4)-bbox(2), bbox(1), bbox(2), [fname '.pdf']);
disp(cmd); system(cmd);