Export PDF: font not found - macos

I am trying to export my figure as a PDF. I run into the problem that when I want to edit it (in this case by Graphic on macOS) that the font appears not to be found by the editor. My question is, how do I solve this? Can I 'install' the fonts used by matplotlib?
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0,1], [0,1])
plt.savefig('test.pdf')
This PDF looks fine in Preview:
But in the editor, it gives gibberish:
Failing solution
Setting
matplotlib.rc("pdf", fonttype=42)
(see this answer).
Partly working solution
What works is to install all matplotlib's fonts. I have followed this answer to find all matplotlib's ttfs, and installed them. This works and solves the problem.
But... This does solve the issues when LaTeX is enabled, by
import matplotlib
matplotlib.rcParams['text.usetex'] = True
How do I install the fonts that matplotlib uses now?
A solution here is to export as SVG. However, for some reason this takes ages on my system (see this bug).

I have found a workaround. This is to convert all fonts to outlines before editing. One way to do this is with GhostScript with the option -dNoOutputFonts, as described in this answer:
gs -o file-with-outlines.pdf -dNoOutputFonts -sDEVICE=pdfwrite file.pdf

What pdf editor are you using? I don't know how to check whether an attempt to solve this is working... but I always use this code to save images in pdf or png:
plt.savefig('test.pdf', edgecolor='none', bbox_inches="tight")

Related

In Colab, why are images not displayed in executed files when they are in an identical code cell?

In Colab, the following code snippet will display (as expected) the image specified:
from google.colab.patches import cv2_imshow
import cv2
#from PIL import Image
img = cv2.imread('drive/MyDrive/beagle2.jpg')
cv2_imshow(img)
If, however, this code is run as a Python file, there is an error:
AttributeError: module 'PIL' has no attribute 'Image'
Why the difference? And what has module 'PIL" got to do with anything?
I have tried various image display methods and while I can get them all to work in a code cell, in an executed file, they either give an error, a text description of the image file or nothing.
I need to run my code as file in order to pass parameters.
Here is the answer:
instead of running
!python yourScript.py
run
%run yourScript.py
and images will display with pyplot,cv2_imshow etc.
cf. How to plot with pyplot from a script file in Google Colab?
This solution took ages to find and why it works is unclear to me. Is it just another not very well documented feature of Colab?
If
from PIL import Image
is put at the top of the file (and only at the top. Why?) then the following description of the image is produced:
<PIL.Image.Image image mode=RGB size=259x201 at 0x7F05007C5DA0>
but the image itself is still not displayed.

Graphviz not supporting UTF-8 encoding

I have created a dot file.which contain some korean language in some node's label .i created png file with help of graphvig tool but that created png doesn't support korean language it appear as square box. if i create svg file then it works fine.
help me how to resolve this.
Also try running dot -v to see what plugins and font files are being loaded. Generally we expect UTF-8 to work (a lot of work was done on this over the years), and text layout through the cairopango driver works well. A downside is that pango now does its own font lookup which is somewhat of a black box to other code. (pango recently dropped fontconfig, which is understandable. We did not ever discover a way to determine if fontconfig failed to find a good match for a given specification - it would cheerfully return e.g. a typewriter font when it could not find any other match.) Hope this helps a little.
Stephen North (for the graphviz project)
I had the same problem, when a .png file is generated, the non-ascii chars is not rendered correctly.
My alternative solution is to use the .svg output (via some command like: dot -Tsvg my_graph.gv), which left the font-finding problem to the svg viewer.
You can open the .svg file with a Web Browser. And most Web Browser also support the save as function to convert the .svg file to .png if you insist on the .png format.
Hope this helpful
I met the same problem, and adding the following lines helped me:
strict digraph {
node [ fontname="Adobe Kaiti Std" ];
edge [ fontname="Adobe Heiti Std" ];
}
Use a tool to convert the SVG file into a PNG. I suggest Batik. You'll have to deal with installing fonts, of course. Alternatively, you can use Inkscape, though that's slightly more of a manual process.
Make sure to define a korean fontname in your graph.

MATLAB newbie: error using "saveas" to save a plot as a pdf file

I am a Mac (10.6.8) user. I have written MATLAB code for plotting calculation results and then saving the plots as pdfs. I use "saveas" (see example below).
I get this error:
??? Error using ==> print at 325
Problem converting PostScript. System returned error: -1.Failed to convert to output format; Ghostscript status: -100.**** Unable to open the initial device, quitting.
Error in ==> saveas at 155
print( h, name, ['-d' dev{i}] )
Error in ==> Results_processor at 1219
saveas(gcf,saveFigTo1, 'pdf')
Here is the relevant piece of code:
calculationResultsPath = '/Me/Projects/ThisProject';
calculationResultsDirectory = strcat( calculationResultsPath,'MATLABProcessedResults' );
mkdir( calculationResultsDirectory );
% ...Code for importing results to be plotted from external files (works fine)...
% ...Code for plotting (works fine)... I get the figures I want.
% The problem is:
saveFigTo1 = strcat(resultsDirectory,'/majorsMgO.pdf')
saveas(gcf,saveFigTo1, 'pdf')
hold off
pause
clf;
Some further information... This worked fine last week when I first wrote it! Since then, I think I updated to Mac OS 10.6.8 from 10.6.7, but nothing else has changed in my code or in the version of Matlab I use (R2009a) (unless I have a very bad memory!).
Also, I came across some older suggestions on similar questions to use "print." I tried using:
print(gcf,'filename'). I did get a pdf, but it would not open in any pdf viewing programme. I assume (but don't know for sure) that this could be related to the fact that I use a Mac. I have noticed that there are a few things (especially related to external file manipulation) that don't run on Mac.
If anyone could help, I would be very grateful.
Update:
I found a GhostScript for Mac and installed it as Chris suggested. Unfortunately, that didn't work. I read on a forum that many Mac users are having problems with MATLAB plots at present, possibly related to java. There was an operating system update (to OS X 10.6.8) last week and that is when the problems began. My code worked before then.
I still have not found a solution to this and I don't think the MATLAB people have either, so if anyone has suggestions about how to save plots WITHOUT using saveas, I would love to hear them. The "print" command does not work for me either--it produces PDFs that I can't open.
I think the problem here is GhostScript dying and not so much Matlab. A Google for that GS error turns up many pages such as this. Is this at all applicable? If you use GS outside of Matlab does it work?
As an aside, you might take a look at this FEX submission export_fig. It has treated me well. Worst case you could output to png and convert to PDF later.
One recommendation I can make is to use a different format that OS X understands and simply convert the result to pdf with a system call
See if the following works:
% Load a test image
im = imread('cameraman.tif');
imshow(im); % display the image
saveas(gcf,'test.tif','tif');
% convert to pdf using a syscall to cupsfilter
!cupsfilter test.tif > test.pdf 2> /dev/null
% open the file with your default pdf viewer
!open test.pdf
If the above is not working, yet another approach is to get the bitmap from the figure window and write it using imwrite. Note, this method doesn't benefit from the nice font scaling features of the saveas and print. This approach assumes the im variable above still exists.
imagesc(im); colormap gray;
% Set the border color to white
set(h,'Color',[1 1 1]);
% Get the image in the figure
frame = getframe(gcf);
imout = frame.cdata;
% on OS X, the stretch window image
% appears in the bottom right corner
% of the image. Remove it.
imout = imout(10:end-9,10:end-9,:);
% Write the image out to a lossless tif
imwrite(imout,'test.tif','tif','Compression','none')
You could then convert the tifs to pdf files as above. The quality of the figure will depend on the figure size. In most cases, I wouldn't use this second approach as saveas handles the fonts nicely. Using getframe is meant only as a workaround to the true problem with saveas.

wkhtmltopdf + mixed photo colors

I have a page with color and black & white images, when I use wkhtmltopdf to generate a pdf from the html file,
I get only the color images, how can I get it to print all the images, I have tried the advance options, but no success.
If I print in grayscale, then all the images are coming, but I don't want grayscale.
Any help?
I figured out how to solve this problem, I tried a trial-and-error method and figured out that if we provided the following parameters all the images irrespective of color or B&W, it would come up
wkhtmltopdf --image-quality 75
NOTE: Any value <= 75 works, higher value print a blank space for B&W images only
This question is old, but I'll add this in case someone has a similar issue and is unable to upgrade.
I found that applying this CSS solved the problem of non-color image rendering for me.
img {opacity: 0.99;}
To follow on from my comment above:
Changing the image quality only helps some cases
I contacted the developer (antialize) and he has now fixed this issue on his staging branch.
There isn't a release yet with this fix, so you will have to compile it yourself.
If you compile using the latest staging branch, all images now work as expected. Remember to compile following the "Installing QT yourself" instructions.
Furthermore, if you want to compile statically, see my note (on the compilation wiki page, made on Dec 19, 2011) about editing two files to allow static compiling of webkit (the 2 files that need to change are /tools/configure/configureapp.cpp and configure).

How to import GIF files into Beamer presentation?

I need to import animations from Maple into my LaTeX/Beamer presentation. I save a file in GIF format. But later I have problems converting that file into PNG. All I get is a static PNG file and can't proceed ((( What's the full code to do that in LaTeX?
You can use the animate package to animate a series of PNGs. To get the series of PNGs from an animated GIF, use a tool like ImageMagick's convert.
Does this help: LINK? (This is the same answer as marcog... just wanted to provide a reference to it being asked previously -- the solution was the same: the animate package).
Also, your OS will matter. I don't know that Linux (not saying you're using it) has any ability to play animated PDFs. I've tried embedding movies using LaTeX and while it "works," you can't actually view them in anything Linux offers yet. Okular is working on it, but last I checked (couple months?) it's not possible yet.
Anyway, just wanted to add that just in case you were doing everything completely right and by chance are not seeing the fruits of your labor since you're using a Linux viewer. Check your work with Acrobat on Windows to be sure.

Resources