Создание двусторонних PDF-файлов Pretty с помощью Quarto

Отказ от ответственности

Я позаимствовал большую часть кода из Создание красивых PDF-файлов с помощью Quarto. Мой код отлично работает с classoption: [oneside], но есть проблемы с classoption: [twoside]. Я был бы очень признателен за любые рекомендации о том, как правильно его отобразить.

---
book:
  title: "Title"
  author: "MYaseen208"
format:
  pdf:
    documentclass: scrreprt
    classoption: [twoside]
  # classoption: [oneside]
    toc: true
    toc-depth: 3
    lot: true
    lof: true
    include-in-header:
      - text: |
          %% load packages
          \usepackage{lipsum}
          \usepackage{geometry}
          \usepackage{xcolor}
          \usepackage{eso-pic}
          \usepackage{fancyhdr}
          \usepackage{sectsty}
          \usepackage{fontspec}
          \usepackage{titlesec}
          
          %% Set page size with a wider right margin
          \geometry{a4paper, total = {170mm,257mm}, left=20mm, top=20mm, bottom=20mm, right=50mm}
          
          %% Let's define some colours
          \definecolor{light}{HTML}{E6E6FA}
          \definecolor{highlight}{HTML}{800080}
          \definecolor{dark}{HTML}{330033}
          
          %% Let's add the border on the right hand side
          \AddToShipoutPicture{% 
              \AtPageLowerLeft{% 
                  \put(\LenToUnit{\dimexpr\paperwidth-3cm},0){% 
                      \color{light}\rule{3cm}{\LenToUnit\paperheight}%
                    }%
               }%
          }
    include-before-body:
      - text: |
          %% Style the page number
          \fancypagestyle{mystyle}{
          \fancyhf{}
          \renewcommand\headrulewidth{0pt}
          \fancyfoot[R]{\thepage}
          \fancyfootoffset{3.5cm}
          }
          \setlength{\footskip}{20pt}
          
          %% style the chapter/section fonts
          \chapterfont{\color{dark}\fontsize{20}{16.8}\selectfont}
          \sectionfont{\color{dark}\fontsize{18}{16.8}\selectfont}
          \subsectionfont{\color{dark}\fontsize{14}{16.8}\selectfont}
          
          %% left align title
          \makeatletter
          \renewcommand{\maketitle}{\bgroup\setlength{\parindent}{0pt}
          \begin{flushleft}
            {\sffamily\huge\textbf{\MakeUppercase{\@title}}} \vspace{0.3cm} \newline
            {\Large {\@subtitle}} \newline
            \@author
          \end{flushleft}\egroup
          }
          \makeatother
---

# Introduction

\lipsum[1-50] 

# Material and Methods

\lipsum[1-20] 

Чего именно вы пытаетесь достичь? Чтобы текст не пересекал цветную границу справа?

Julian 30.05.2023 12:18

Спасибо @Julian за интерес к моей проблеме. Для нечетных страниц мне нужна рамка справа, а для четных страниц граница должна быть слева для двусторонней книги.

MYaseen208 30.05.2023 12:41
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
6
2
172
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Вы можете проверить, является ли страница четной или нечетной, и соответствующим образом разместить синюю полосу:

\makeatletter
\AddToShipoutPicture{%
\if@twoside
\ifodd\c@page
    \AtPageLowerLeft{%
        \put(\LenToUnit{\dimexpr\paperwidth-3cm},0){%
            \color{light}\rule{3cm}{\LenToUnit\paperheight}%
          }%
     }%
\else
    \AtPageLowerLeft{%
        \put(\LenToUnit{0cm},0){%
            \color{light}\rule{3cm}{\LenToUnit\paperheight}%
          }%
     }%
\fi
\else
    \AtPageLowerLeft{%
        \put(\LenToUnit{\dimexpr\paperwidth-3cm},0){%
            \color{light}\rule{3cm}{\LenToUnit\paperheight}%
          }%
     }%
\fi
}
\makeatother

Полный документ:

% Options for packages loaded elsewhere
\PassOptionsToPackage{unicode}{hyperref}
\PassOptionsToPackage{hyphens}{url}
\PassOptionsToPackage{dvipsnames,svgnames,x11names}{xcolor}
%
\documentclass[
  letterpaper,
  DIV=11,
  numbers=noendperiod,
  twoside
  ]{scrreprt}

\usepackage{amsmath,amssymb}
\usepackage{iftex}
\ifPDFTeX
  \usepackage[T1]{fontenc}
  \usepackage[utf8]{inputenc}
  \usepackage{textcomp} % provide euro and other symbols
\else % if luatex or xetex
  \usepackage{unicode-math}
  \defaultfontfeatures{Scale=MatchLowercase}
  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
\fi
\usepackage{lmodern}
\ifPDFTeX\else  
    % xetex/luatex font selection
\fi
% Use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\IfFileExists{microtype.sty}{% use microtype if available
  \usepackage[]{microtype}
  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\makeatletter
\@ifundefined{KOMAClassName}{% if non-KOMA class
  \IfFileExists{parskip.sty}{%
    \usepackage{parskip}
  }{% else
    \setlength{\parindent}{0pt}
    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
}{% if KOMA class
  \KOMAoptions{parskip=half}}
\makeatother
\usepackage{xcolor}
\setlength{\emergencystretch}{3em} % prevent overfull lines
\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
% Make \paragraph and \subparagraph free-standing
\ifx\paragraph\undefined\else
  \let\oldparagraph\paragraph
  \renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
  \let\oldsubparagraph\subparagraph
  \renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi


\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}\usepackage{longtable,booktabs,array}
\usepackage{calc} % for calculating minipage widths
% Correct order of tables after \paragraph or \subparagraph
\usepackage{etoolbox}
\makeatletter
\patchcmd\longtable{\par}{\if@noskipsec\mbox{}\fi\par}{}{}
\makeatother
% Allow footnotes in longtable head/foot
\IfFileExists{footnotehyper.sty}{\usepackage{footnotehyper}}{\usepackage{footnote}}
\makesavenoteenv{longtable}
\usepackage{graphicx}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
% Set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother

%% load packages
\usepackage{lipsum}
\usepackage{geometry}
\usepackage{xcolor}
\usepackage{eso-pic}
\usepackage{fancyhdr}
\usepackage{sectsty}
%\usepackage{fontspec}
\usepackage{titlesec}

%% Set page size with a wider right margin
\geometry{a4paper, total = {170mm,257mm}, left=20mm, top=20mm, bottom=20mm, right=50mm}

%% Let's define some colours
\definecolor{light}{HTML}{E6E6FA}
\definecolor{highlight}{HTML}{800080}
\definecolor{dark}{HTML}{330033}

%% Let's add the border on the right hand side
\makeatletter
\AddToShipoutPicture{%
\if@twoside
\ifodd\c@page
    \AtPageLowerLeft{%
        \put(\LenToUnit{\dimexpr\paperwidth-3cm},0){%
            \color{light}\rule{3cm}{\LenToUnit\paperheight}%
          }%
     }%
\else
    \AtPageLowerLeft{%
        \put(\LenToUnit{0cm},0){%
            \color{light}\rule{3cm}{\LenToUnit\paperheight}%
          }%
     }%
\fi
\else
    \AtPageLowerLeft{%
        \put(\LenToUnit{\dimexpr\paperwidth-3cm},0){%
            \color{light}\rule{3cm}{\LenToUnit\paperheight}%
          }%
     }%
\fi
}
\makeatother
\KOMAoption{captions}{tableheading}
\makeatletter
\makeatother
\makeatletter
\makeatother
\makeatletter
\@ifpackageloaded{caption}{}{\usepackage{caption}}
\AtBeginDocument{%
\ifdefined\contentsname
  \renewcommand*\contentsname{Table of contents}
\else
  \newcommand\contentsname{Table of contents}
\fi
\ifdefined\listfigurename
  \renewcommand*\listfigurename{List of Figures}
\else
  \newcommand\listfigurename{List of Figures}
\fi
\ifdefined\listtablename
  \renewcommand*\listtablename{List of Tables}
\else
  \newcommand\listtablename{List of Tables}
\fi
\ifdefined\figurename
  \renewcommand*\figurename{Figure}
\else
  \newcommand\figurename{Figure}
\fi
\ifdefined\tablename
  \renewcommand*\tablename{Table}
\else
  \newcommand\tablename{Table}
\fi
}
\@ifpackageloaded{float}{}{\usepackage{float}}
\floatstyle{ruled}
\@ifundefined{c@chapter}{\newfloat{codelisting}{h}{lop}}{\newfloat{codelisting}{h}{lop}[chapter]}
\floatname{codelisting}{Listing}
\newcommand*\listoflistings{\listof{codelisting}{List of Listings}}
\makeatother
\makeatletter
\@ifpackageloaded{caption}{}{\usepackage{caption}}
\@ifpackageloaded{subcaption}{}{\usepackage{subcaption}}
\makeatother
\makeatletter
\@ifpackageloaded{tcolorbox}{}{\usepackage[skins,breakable]{tcolorbox}}
\makeatother
\makeatletter
\@ifundefined{shadecolor}{\definecolor{shadecolor}{rgb}{.97, .97, .97}}
\makeatother
\makeatletter
\makeatother
\makeatletter
\makeatother
\ifLuaTeX
  \usepackage{selnolig}  % disable illegal ligatures
\fi
\IfFileExists{bookmark.sty}{\usepackage{bookmark}}{\usepackage{hyperref}}
\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
\urlstyle{same} % disable monospaced font for URLs
\hypersetup{
  colorlinks=true,
  linkcolor = {blue},
  filecolor = {Maroon},
  citecolor = {Blue},
  urlcolor = {Blue},
  pdfcreator = {LaTeX via pandoc}}

\author{}
\date{}

\begin{document}
%% Style the page number
\fancypagestyle{mystyle}{
\fancyhf{}
\renewcommand\headrulewidth{0pt}
\fancyfoot[R]{\thepage}
\fancyfootoffset{3.5cm}
}
\setlength{\footskip}{20pt}

%% style the chapter/section fonts
\chapterfont{\color{dark}\fontsize{20}{16.8}\selectfont}
\sectionfont{\color{dark}\fontsize{18}{16.8}\selectfont}
\subsectionfont{\color{dark}\fontsize{14}{16.8}\selectfont}

%% left align title
\makeatletter
\renewcommand{\maketitle}{\bgroup\setlength{\parindent}{0pt}
\begin{flushleft}
  {\sffamily\huge\textbf{\MakeUppercase{\@title}}} \vspace{0.3cm} \newline
  {\Large {\@subtitle}} \newline
  \@author
\end{flushleft}\egroup
}
\makeatother

\ifdefined\Shaded\renewenvironment{Shaded}{\begin{tcolorbox}[boxrule=0pt, sharp corners, interior hidden, borderline west = {3pt}{0pt}{shadecolor}, frame hidden, enhanced, breakable]}{\end{tcolorbox}}\fi

\renewcommand*\contentsname{Table of contents}
{
\hypersetup{linkcolor=}
\setcounter{tocdepth}{2}
\tableofcontents
}
\listoffigures
\listoftables
\hypertarget{introduction}{%
\chapter{Introduction}\label{introduction}}

\lipsum[1-50]

\hypertarget{material-and-methods}{%
\chapter{Material and Methods}\label{material-and-methods}}

\lipsum[1-20]

\end{document}

замените classoption: [twoside]" на:

classoption:

 - twoside  

Как это поможет, если боковая панель жестко закодирована, чтобы быть с правой стороны? Если вы проверите промежуточный файл .tex, вы увидите, что [twoside] анализируется правильно.

samcarter_is_at_topanswers.xyz 07.06.2023 21:00

Другие вопросы по теме