
Я ищу надежный способ конвертировать PDF-файл из файла Latex в SVG для отображения в браузере.
\documentclass{article}
\pagenumbering{gobble}
\usepackage{blkarray}
\usepackage{xcolor}
\definecolor{darkred}{rgb}{0.55, 0.0, 0.0}
% -----------------------------------------------------------------------------------------------
\begin{document}
\begin{blockarray}{rrrrrrrrrr}
\begin{block}{rrrr(cccc|c)!{\quad}l}
& & & & 1 & 2 & 2 & 1 & 8 & the pivot is in row 2, col 2\\
& & & & 0 & {\colorbox{yellow}{\color{darkred}{$\boxed{1}$}}} & -1 & 0 & 0 & It will be multiplied by\\
& & & & 0 & {\colorbox{yellow}{\color{darkred}{-2}}} & 1 & -2 & -5 & entries in column 1 of $E$ \\
& & & & 0 & {\colorbox{yellow}{\color{darkred}{\ 1}}} & -1 & 1 & 2 & \\
\end{block}
\end{blockarray}
\end{document}
- Я использовал
\documentclass{standalone}
то, что не сработало, и в итоге мне пришлось удалить номер страницы и использовать следующий уродливый скрипт оболочки
!/bin/sh
latexmk -pdflatex $1.tex && \
latexmk -pdflatex -c $1.tex && \
pdf2svg $1.pdf /tmp/temp_$1.svg && \
inkscape -D --without-gui --file=/tmp/temp_$1.svg --export-plain-svg $1.svg
Вопросы
- Есть ли более простой способ создать svg, чтобы изображение было обрезано до фактического размера? (опция -D для inkscape)
- Есть ли более простой способ создать PDF-файл, чтобы отображалось только это изображение, а не вся страница?
- Скобки, окружающие матрицу, путаются при большинстве моих попыток. Что мне нужно сделать, чтобы убедиться, что скобки будут правильно отображены
- может ли какое-либо решение использовать xelatex вместо pdflatex?
решение1
Вместо pdf2svg
, который не поддерживается, я бы использовал , dvisvgm
который является частью TeXLive/MiKTeX и активно поддерживается.
Сочетание --exact
и --zoom=-1
обрезает вывод до видимого содержимого и делает его адаптивным, что облегчает встраивание в HTML (опции описаны ниже).здесь).
latex input
dvisvgm --exact --zoom=-1 --font-format=woff2 input
\documentclass{article}
\pagestyle{empty}
\usepackage{nicematrix}
\usepackage{blkarray}
\usepackage{xcolor}
\definecolor{darkred}{rgb}{0.55, 0.0, 0.0}
% -----------------------------------------------------------------------------------------------
\begin{document}
\begin{blockarray}{rrrrrrrrrr}
\begin{block}{rrrr(cccc|c)!{\quad}l}
& & & & 1 & 2 & 2 & 1 & 8 & the pivot is in row 2, col 2\\
& & & & 0 & {\colorbox{yellow}{\color{darkred}{$\boxed{1}$}}} & -1 & 0 & 0 & It will be multiplied by\\
& & & & 0 & {\colorbox{yellow}{\color{darkred}{-2}}} & 1 & -2 & -5 & entries in column 1 of $E$ \\
& & & & 0 & {\colorbox{yellow}{\color{darkred}{\ 1}}} & -1 & 1 & 2 & \\
\end{block}
\end{blockarray}
\end{document}
решение2
Просто добавьте недостающее amsmath
.
\documentclass{standalone}
\usepackage{amsmath}
\usepackage{blkarray}
\usepackage{xcolor}
\definecolor{darkred}{rgb}{0.55, 0.0, 0.0}
% -----------------------------------------------------------------------------------------------
\begin{document}
\begin{blockarray}{rrrrrrrrrr}
\begin{block}{rrrr(cccc|c)!{\quad}l}
& & & & 1 & 2 & 2 & 1 & 8 & the pivot is in row 2, col 2\\
& & & & 0 & {\colorbox{yellow}{\color{darkred}{$\boxed{1}$}}} & -1 & 0 & 0 & It will be multiplied by\\
& & & & 0 & {\colorbox{yellow}{\color{darkred}{-2}}} & 1 & -2 & -5 & entries in column 1 of $E$ \\
& & & & 0 & {\colorbox{yellow}{\color{darkred}{\ 1}}} & -1 & 1 & 2 & \\
\end{block}
\end{blockarray}
\end{document}
Затем скомпилируйте и конвертируйте из PDF в SVG, как вы предложили.
#!/bin/bash
latexmk -pdflatex $1.tex && \
latexmk -pdflatex -c $1.tex && \
pdf2svg $1.pdf $1.svg
решение3
Каждая из цепочек инструментов дает сбой при различных обстоятельствах, в зависимости от движка Latex, класса документа и используемых пакетов.
Я добавляю текущую (python/linux) версию функции, которая строит цепочку инструментов tex_program -> svg_converter -> svg_crop
как список параметров команды, которые можно использовать в вызове python для запуска подпроцесса. Параметр не nexec
является числом вызовов tex_program
. Он не применим для всех комбинаций...
def build_commands( tex_program=["pdflatex"], svg_converter=[["pdf2svg"],".pdf"], use_xetex=False, use_dvi=False, crop=False, nexec=1):
if isinstance( tex_program, (list,)) is False:
tex_program = [tex_program]
if tex_program[0] == "pdflatex":
if use_xetex is True:
if use_dvi is True:
if nexec > 1:
_tex_program = ["xelatex", "--no-pdf", "-etex" ]
_svg_converter = [["dvisvgm", "--font-format=woff2", "--exact"], ".xdv"]
else:
_tex_program = ["latexmk", "-xelatex", "-etex" ]
_svg_converter = [["dvisvgm", "--font-format=woff2", "--exact"], ".xdv"]
else:
if nexec > 1:
_tex_program = ["xelatex", "-etex" ]
_svg_converter = [["pdf2svg"], ".pdf"]
else:
_tex_program = ["latexmk", "-xelatex", "-etex" ]
_svg_converter = [["pdf2svg"], ".pdf"]
else:
if use_dvi is True:
_tex_program = ["latexmk", "-etex", "-dvi" ]
_svg_converter = [["dvisvgm", "--font-format=woff2", "--exact"], ".dvi"]
else:
_tex_program = ["latexmk", "-etex", "-pdf" ]
_svg_converter = [["pdf2svg"], ".pdf"]
else:
_tex_program = tex_program
_svg_converter = svg_converter
if crop:
_svg_crop = (["inkscape", "-D", "--without-gui", "--file"], ["--export-plain-svg"])
else:
_svg_crop = None
return _tex_program, _svg_converter,_svg_crop
Для вызова программ я использую следующий код:
tex_program.append( tex_path )
for _ in range(nexec-1):
run_subprocess(tex_program, cwd=working_dir)
check_output(tex_program, cwd=working_dir)
svg_program = svg_converter[0] + [pdf_path, svg_path]
check_output(svg_program, cwd=working_dir)
if svg_crop is not None:
crop_program = svg_crop[0] + [svg_path] + svg_crop[1] + [svg_path]
check_output( crop_program, cwd=working_dir)