Как увеличить шрифт в латехе
Перейти к содержимому

Как увеличить шрифт в латехе

  • автор:

Text Formatting with LaTeX

The chapter begins with an overview of basic text formatting commands in LaTeX, including commands for changing font styles, font sizes, and text alignment. It then covers more advanced text formatting topics, such as creating lists and bullet points, using colors and backgrounds, and working with tables and figures. In addition to these basic formatting topics, the chapter also covers more advanced text formatting techniques, including using custom fonts, creating and using macros for text formatting, and working with special characters and symbols. Throughout the article, readers will find clear explanations and examples of each text formatting technique, as well as tips and best practices for using LaTeX to format text in the most efficient and effective way possible. Whether you’re new to LaTeX or just looking to improve your text formatting skills, this article is the perfect resource to help you get started.

Introduction to text formatting in LaTeX

LaTeX is a powerful tool for typesetting documents, particularly technical and scientific documents. One of its strengths is its ability to easily format text, with commands that allow you to change the font, size, and style of your text.

Here are some of the basic text formatting commands in LaTeX:

  1. \textbf: This command makes the text inside it bold.
  2. \textit: This command makes the text inside it italic.
  3. \underline: This command underlines the text inside it.
  4. \emph: This command emphasizes the text inside it, usually by italicizing it.
  5. \textrm: This command sets the text inside it to a Roman font.
  6. \textsf: This command sets the text inside it to a sans-serif font.
  7. \texttt: This command sets the text inside it to a typewriter font.
  8. \textsc: This command sets the text inside it to small caps.
  9. \textnormal: This command sets the text inside it back to the default font.

These commands can be used individually or in combination with each other to achieve the desired formatting. Additionally, there are variations of these commands that allow you to change the size of the text as well.

For example, to make a sentence bold and italicized, you can use the following command:

By using these basic text formatting commands, you can create professional-looking documents with ease.

LaTeX provides a variety of commands for text formatting. Here’s a brief explanation of some of the most commonly used commands:

Font styles

  • \textbf : This command makes the text inside it bold.
  • \textit : This command makes the text inside it italic.
  • \underline : This command underlines the text inside it.
  • \emph : This command emphasizes the text inside it, usually by italicizing it.
  • \textsc : This command sets the text inside it to small caps.

Font sizes

  • \tiny : This command sets the text size to tiny.
  • \small : This command sets the text size to small.
  • \normalsize : This command sets the text size to normal.
  • \large : This command sets the text size to large.
  • \Large : This command sets the text size to extra large.

Text alignment

  • \centering : This command centers the text on the page.
  • \raggedright : This command aligns the text to the left.
  • \raggedleft : This command aligns the text to the right.

By combining these commands, you can create a wide variety of text formatting options. For example, to create a paragraph of centered, bold, large text, you can use the following commands:

And to create a paragraph of left-aligned, italicized, small text, you can use the following commands:

By using these commands, you can create documents that are both visually appealing and easy to read.

In LaTeX, curly braces <> and backslashes \ are used extensively in commands to indicate the scope of the command and its parameters.

Curly braces

Curly braces are used to enclose the arguments or parameters of a LaTeX command. The text enclosed by the curly braces is affected by the command. For example, in the command \textbf , the text “This text is bold.” is enclosed in curly braces and is made bold by the \textbf command.

Curly braces are also used to indicate the scope of some environments in LaTeX, such as the center environment:

In this example, the center environment is delimited by the curly braces and any text within the environment is centered.

Backslashes

Backslashes are used to indicate the beginning of a LaTeX command. For example, the command \textbf makes text bold, and the command \begin starts an environment.

Backslashes are also used to introduce special characters, such as the tilde

and the percent sign % , which have special meaning in LaTeX. To print these characters literally, you must precede them with a backslash, like so: \

Backslashes are also used to create special characters that are not available on a standard keyboard. For example, to create the German umlaut character ä , you would use the command \» .

Overall, curly braces and backslashes are essential to the structure of LaTeX commands, allowing for precise formatting and control over text output.

In LaTeX, an environment is a section of the document that has a specific formatting or behavior. Environments are delimited by a \begin command and an \end command, where env is the name of the environment.

Environments are used extensively in LaTeX for text formatting, and are a powerful tool for creating structured documents. Here are some examples of common environments used for text formatting:

center environment

The center environment is used to center text on the page. Any text enclosed between \begin

and \end
is centered. For example:

quote environment

The quote environment is used to indicate quoted text. It indents the text and adds vertical space before and after the text. For example:

itemize and enumerate environments

The itemize environment is used to create bulleted lists, while the enumerate environment is used to create numbered lists. For example:

verbatim environment

The verbatim environment is used to typeset text exactly as it appears in the input file, without interpreting any special characters or formatting. For example:

Environments can also be nested inside other environments, allowing for even more complex formatting. Overall, environments are a powerful tool in LaTeX for creating structured and well-formatted documents.

Basic text formatting commands

In LaTeX, font styles can be changed using commands like \textbf , \textit , and \texttt . These commands are used to change the font weight, font style, and font family respectively. Here’s a brief explanation of each command:

\textbf

The \textbf command is used to make text bold. Any text enclosed in the command’s curly braces <> will be displayed in a bold font. For example:

\textit

The \textit command is used to make text italic. Any text enclosed in the command’s curly braces <> will be displayed in an italic font. For example:

\texttt

The \texttt command is used to make text appear in a monospace font. This is commonly used for displaying code snippets or other text that needs to maintain a consistent character width. For example:

Note that these commands only affect the text enclosed in their curly braces. If you want to apply a font style to an entire paragraph, you can use an environment like <\bfseries . >or \begin. \end . For example:

Overall, the commands \textbf , \textit , and \texttt are useful tools for changing font styles in LaTeX, and can be used to add emphasis and improve readability in documents.

In LaTeX, font sizes can be changed using commands like \tiny , \small , and \large . These commands are used to change the size of the text, with \tiny being the smallest and \Huge being the largest. Here’s a brief explanation of each command:

The \tiny command is used to make text very small. This is useful for footnotes or other text that needs to be very small. For example:

\small

The \small command is used to make text smaller than the default size. This is useful for captions or other text that needs to be slightly smaller than the main text. For example:

\large

The \large command is used to make text larger than the default size. This is useful for headings or other text that needs to stand out from the main text. For example:

Note that these commands only affect the text enclosed in their curly braces. If you want to apply a font size to an entire paragraph, you can use an environment like \begin. \end or \begin. \end . For example:

Overall, the commands \tiny , \small , and \large are useful tools for changing font sizes in LaTeX, and can be used to improve the readability and hierarchy of text in documents.

In LaTeX, text alignment can be changed using commands like \centering , \raggedright , and \raggedleft . These commands are used to change the alignment of text within a paragraph. Here’s a brief explanation of each command:

\centering

The \centering command is used to center text within a paragraph. Any text that follows the command will be centered until a new alignment command is used. For example:

\raggedright

The \raggedright command is used to align text to the left within a paragraph. Any text that follows the command will be aligned to the left until a new alignment command is used. For example:

\raggedleft

The \raggedleft command is used to align text to the right within a paragraph. Any text that follows the command will be aligned to the right until a new alignment command is used. For example:

Note that these commands only affect the text that follows them. If you want to apply an alignment to an entire document, you can use an environment like \begin

. \end
or \begin. \end . For example:

Overall, the commands \centering , \raggedright , and \raggedleft are useful tools for changing text alignment in LaTeX, and can be used to improve the visual appeal and readability of documents.

Advanced text formatting commands

In LaTeX, lists and bullet points can be created using the itemize and enumerate environments. These environments provide a convenient way to create organized and structured lists. Here’s a brief explanation of each environment:

itemize

The itemize environment is used to create an unordered list, or a list of items that do not have a specific order or sequence. Each item in the list is preceded by a bullet point. For example:

This will create a list like this:

  • Item 1
  • Item 2
  • Item 3

enumerate

The enumerate environment is used to create an ordered list, or a list of items that have a specific order or sequence. Each item in the list is preceded by a number or letter. For example:

This will create a list like this:

  1. Item 1
  2. Item 2
  3. Item 3

Note that you can also nest lists inside each other. For example:

This will create a list like this:

  1. Item 1
  2. Item 2
    • Subitem 1
    • Subitem 2
  3. Item 3

Overall, the itemize and enumerate environments are useful tools for creating lists and bullet points in LaTeX, and can be used to organize information and improve the readability of documents.

In LaTeX, colors and backgrounds can be added to text and elements using the xcolor package. This package provides a variety of color models and options for customizing the appearance of text and other elements in your document.

Here’s a brief explanation of how to use the xcolor package:

Loading the Package

To use the xcolor package, you need to load it in the preamble of your document using the following command:

Defining Colors

The xcolor package provides several color models to define colors, including RGB, CMYK, and HTML. To define a color, you can use the \definecolor command, which has the following syntax:

For example, to define a color called “myblue” using the RGB model with values 50,100,200, you can use the following command:

Using Colors

Once you have defined a color, you can use it in your document using the \textcolor command, which has the following syntax:

For example, to make the word “Hello” appear in blue, you can use the following command:

Adding Backgrounds

You can also add backgrounds to elements using the xcolor package. The \colorbox command can be used to create a colored box behind text, and the \pagecolor command can be used to change the background color of a page. For example:

This will create a blue box behind the word “Hello”.

This will change the background color of the entire page to blue.

Overall, the xcolor package provides a wide range of options for adding colors and backgrounds to your documents in LaTeX, and can be used to enhance the visual appeal and readability of your work.

In LaTeX, tables and figures can be created using the tabular and float environments. These environments provide a convenient way to organize and present data in a structured format. Here’s a brief explanation of each environment:

tabular

The tabular environment is used to create tables with rows and columns of data. This environment takes one required argument that specifies the alignment of the columns (e.g., l for left-aligned, c for centered, r for right-aligned) and one optional argument that specifies the width of the table. Within the tabular environment, you use the & symbol to separate cells in a row, and the \\ symbol to indicate the end of a row. For example:

This will create a table like this:

Left Center Right
1 2 3
4 5 6

float

The float environment is used to create floating objects, such as figures and tables, that can be placed anywhere in the document. This environment takes one optional argument that specifies the placement of the object (e.g., h for here, t for top, b for bottom, p for a separate page). Within the float environment, you use the caption command to add a caption to the object. For example:

This will create a floating figure with a caption and label.

This will create a floating table with a caption and label.

Overall, the tabular and float environments are useful tools for creating tables and figures in LaTeX, and can be used to present data and information in a clear and organized manner.

Customizing text formatting with LaTeX

LaTeX allows you to use different fonts in your document, and the fontspec package provides an easy way to load and use custom fonts. Here are the basic steps to use custom fonts with the fontspec package:

  1. Install the font: First, you need to make sure that the custom font you want to use is installed on your system. You can download fonts from various sources, such as Google Fonts or Adobe Fonts.
  2. Load the fontspec package: The fontspec package is required to work with custom fonts in LaTeX. You can load the package in the preamble of your document using the following command:
  1. Set the font: Once the package is loaded, you can set the font using the \setmainfont command. This command takes the font name as its argument. For example, to use the custom font “MyFont” in your document, you can use the following command:

You can also specify various font features, such as the font size and style, using optional arguments. For example:

This sets the main font to “MyFont-Regular” and specifies the bold, italic, and bold italic variants using the BoldFont , ItalicFont , and BoldItalicFont options. The SizeFeatures option sets the font size to 12 points. 4. Use the font: Once the font is set, you can use it in your document just like any other font. For example:

This will produce a document with the main font set to “MyFont” and the text “This is some text in MyFont.”

Overall, the fontspec package is a powerful tool for working with custom fonts in LaTeX, and allows you to easily set and use different fonts in your documents.

Macros are commands that you can define in LaTeX to simplify the formatting of your document. You can define your own macros for text formatting by using the \newcommand or \renewcommand commands in the preamble of your document.

Here is an example of creating and using macros for text formatting:

Suppose you want to format all instances of a certain term in your document in bold. You can define a macro that will automatically apply the formatting for you:

Here, we define a new command \myterm that takes one argument, and formats it in bold using the \textbf command.

Now, you can use the \myterm command anywhere in your document to format the term in bold:

This will produce output with the term “central limit theorem” in bold.

You can also redefine existing commands using the \renewcommand command. For example, if you want to redefine the \section command to always use a certain font size and style, you can do:

Here, we redefine the \section command to use the \Large font size and \textbf font style.

Using macros can greatly simplify formatting in your document and save you time and effort. However, it is important to use them sparingly and with care, as overuse can make your code harder to read and understand.

When working with LaTeX, you may need to use special characters and symbols that are not available on your keyboard or in the default fonts. To handle these special characters and symbols, you can use packages like inputenc and fontenc .

The inputenc package allows you to specify the character encoding of your input file. This is important because different operating systems and text editors may use different default encodings, and LaTeX may not be able to handle special characters correctly if the encoding is not specified. You can load the package in the preamble of your document using the following command:

The encoding option specifies the encoding you are using. Common encodings include utf8 for Unicode text and latin1 for ISO-8859-1 text. For example, if your input file is saved in UTF-8 encoding, you can use the following command:

The fontenc package allows you to select the font encoding for your document. This is important because different font encodings may support different symbols and characters. You can load the package in the preamble of your document using the following command:

The T1 option selects the font encoding. T1 encoding is recommended because it supports a wide range of symbols and characters.

Here is an example of using the inputenc and fontenc packages:

This will produce output with the special characters displayed correctly.

Overall, the inputenc and fontenc packages are important tools for working with special characters and symbols in LaTeX, and can help you ensure that your document is displayed correctly.

Best practices for text formatting with LaTeX

When it comes to choosing font styles and sizes for different types of documents in LaTeX, there are several factors to consider, such as the purpose of the document, the intended audience, and the style guidelines or requirements for the document. Here are some general guidelines to help you choose appropriate font styles and sizes for different types of documents:

  1. Academic papers: For academic papers such as research articles or theses, it is common to use a serif font such as Times New Roman or Computer Modern. The font size is typically 10-12 points for the body text, and headings and subheadings may be slightly larger (12-14 points). It is also important to use appropriate line spacing and margin sizes to ensure readability.
  2. Presentations: For presentations, sans-serif fonts such as Arial or Helvetica are often used for their clean and modern look. The font size should be large enough to be readable from a distance, typically 18-24 points for the body text, and larger for headings and subheadings.
  3. Business documents: For business documents such as memos or reports, it is important to use a professional and easy-to-read font such as Calibri or Helvetica. The font size should be 10-12 points for the body text, and headings and subheadings may be slightly larger (12-14 points). It is also important to use appropriate spacing and formatting to ensure readability and a professional appearance.
  4. Creative documents: For creative documents such as invitations or posters, it may be appropriate to use more decorative or stylized fonts such as Brush Script or Gotham. The font size should be chosen to fit the design and intended audience, but should be large enough to be readable.

In general, it is important to choose font styles and sizes that are appropriate for the intended purpose and audience of the document, and to ensure readability and consistency throughout the document. It is also important to follow any specific style guidelines or requirements for the document, such as those provided by academic or professional organizations.

Text formatting errors can detract from the professionalism and readability of your document. Here are some common errors to avoid when formatting text in LaTeX:

  1. Inconsistent font styles and sizes: Make sure to use consistent font styles and sizes throughout your document, especially for headings and subheadings. Inconsistencies can make your document appear unprofessional and difficult to read.
  2. Overuse of bold or italic text: Bold and italic text can be useful for emphasis, but overusing them can make your document appear cluttered and difficult to read. Use these formatting options sparingly and only for important information.
  3. Incorrect use of line breaks: Avoid using multiple line breaks or excessive spacing to create white space in your document. Use paragraph spacing and formatting options instead to create a consistent and professional appearance.
  4. Inappropriate font choices: Make sure to choose a font that is appropriate for the purpose and audience of your document. Some fonts may be difficult to read or appear unprofessional in certain contexts.
  5. Ignoring spacing and alignment: Proper spacing and alignment can greatly improve the readability and appearance of your document. Make sure to use appropriate spacing and alignment options, such as \raggedright or \centering, to create a professional and consistent appearance.
  6. Incorrect use of quotation marks and dashes: Use appropriate quotation marks and dashes for your language and style guidelines. Inconsistent or incorrect usage can make your document appear unprofessional and difficult to read.
  7. Neglecting proofreading: Always proofread your document carefully to ensure that formatting errors are caught and corrected. Even small errors can detract from the professionalism of your document.

By avoiding these common text formatting errors, you can ensure that your document appears professional, polished, and easy to read.

Efficient text formatting in LaTeX can save you time and effort while creating professional and polished documents. Here are some tips to help you format text efficiently in LaTeX:

  1. Use templates and pre-defined styles: Many LaTeX editors offer pre-defined styles and templates for common document types such as articles, presentations, and reports. Using these templates can save you time and ensure consistency throughout your document.
  2. Use packages to simplify formatting: LaTeX offers many packages that simplify common formatting tasks such as tables, figures, and mathematical equations. Using these packages can save you time and effort while creating professional-looking documents.
  3. Use macros to automate formatting: Macros allow you to define custom commands that can automate formatting tasks and save you time. For example, you can define a macro for frequently used formatting commands such as \textbf or \textit.
  4. Use keyboard shortcuts: Many LaTeX editors offer keyboard shortcuts for common formatting tasks such as bolding or italicizing text. Learning these shortcuts can save you time and increase your productivity.
  5. Use comments to organize your code: Comments allow you to add notes and explanations to your LaTeX code. Using comments to organize your code can make it easier to navigate and modify your document.
  6. Preview your document frequently: Previewing your document frequently can help you catch formatting errors and ensure that your document appears as intended. Many LaTeX editors offer real-time previewing of your document as you type.

By using these tips for efficient text formatting in LaTeX, you can save time and effort while creating professional and polished documents.

latex Задать размер шрифта для всего документа, нестандартный размер — например 14 (латех) размер шрифта не изменяется

vedro-compota's picture

Нет стилевой опции 14pt, т.к. это — нестандартный размер шрифта (стандарт — 10,11 или 12), поэтому подключаем пакет extsizes:

Поэтому с помощью \documentclass сделать шрифт 14-ым не получиться:

Осваиваем LaTeX за 30 минут

LaTEX (произносится как «лэйтех» или «латех») представляет собой инструмент для создания профессиональных документов. В его основе лежит парадигма редактирования WYSIWYM (что вижу, то и подразумеваю), то есть от пользователя требуется сосредоточиться только на содержимом документа, оставив его форматирование программе. Вместо ручного распределения текста по странице, как это делается в Microsoft Word или LibreOffice Writer, можно просто его вводить, позволив LaTeX заняться остальным.

Зачем нужен LaTeX?

Этот инструмент используется повсеместно для создания научных документов, написания книг, а также многих других форм публикаций. Он позволяет не только создавать красиво оформленные документы, но также дает пользователям возможность очень быстро реализовывать такие сложные элементы печатного набора, как математические выражения, таблицы, ссылки и библиографии, получая согласованную разметку по всем разделам.

Благодаря доступности большого числа открытых библиотек (об этом чуть позже) возможности LaTEX становятся практически безграничны. Эти библиотеки расширяют возможности пользователей еще больше, позволяя добавлять сноски, рисовать схемы и пр.

Одна из наиболее веских причин, по которой многие используют LaTeX, заключается в отделении содержания документа от его стиля. Это означает, что после написания содержимого, можно с легкостью изменять его внешний вид. Аналогичным образом, можно создать один стиль документа и использовать его для стандартизации внешнего вида других.

Это позволяет научным журналам создавать шаблоны для предлагаемых на рассмотрение материалов. Такие шаблоны имеют заданную разметку, в результате чего добавить остается лишь содержание. На деле существуют сотни подобных шаблонов, начиная с различных резюме и заканчивая презентациями слайдов.

Пишем первый документ

Изначально нам потребуется новый проект, начать который можно либо создав файл .tex , либо через Overleaf. Возьмем простейший пример:

Здесь мы видим, что LaTeX уже позаботился о первом элементе форматирования, сделав отступ в начальной строке абзаца. Теперь более подробно рассмотрим, за что отвечает каждая часть кода.

Первая строка объявляет тип документа, называемый классом. Класс определяет общее представление документа. Для разных типов документов требуются разные классы, то есть для CV/резюме будет использоваться свой класс, а для научного труда свой. В данном случае классом является article , самый простой и распространенный в LaTeX. Другие типы документов, с которыми вам, возможно, придется работать, могут потребовать использования других классов, например book или report .

После этого мы пишем содержание документа, заключенное в теги \begin и \end , представляющие его тело. Можете начать писать здесь текст и при желании вносить в него изменения.

Чтобы увидеть результат этих изменений в PDF, документ нужно скомпилировать. В Overleaf для этого нужно просто нажать Recompile. (Также можете настроить проект на автоматическую перекомпиляцию в процессе редактирования файлов, нажав на небольшую стрелку рядом с кнопкой Recompile и установив Auto Compile как On).

Если вы используете базовый текстовый редактор, например gedit, emacs, vim, sublime, блокнот и пр., то нужно будет компилировать документ вручную. Для этого просто выполните в терминале pdflatex <your document> . Подробнее об этом процессе можете почитать здесь.

При использовании специального редактора LaTeX вроде TeXmaker или TeXworks нужно просто нажать кнопку Recompile. Если не знаете, где она находится, обратитесь к документации.

Теперь, когда вы разобрались, как добавлять в документ содержимое, следующим шагом будет его именование. Для этого необходимо вкратце разобрать преамбулу.

Преамбула документа

В предыдущем примере текст вводился после команды \begin . Все, что содержится в файле .tex до этого места, называется преамбулой. В ней можно определить тип создаваемого документа, используемый язык, нужные библиотеки (подробнее позже) и ряд других элементов. Вот пример типичной преамбулы:

А вот подробное разъяснение каждой строки:

Как уже говорилось, этой командой определяется тип документа. В нее также можно передавать дополнительные параметры, включенные в квадратные скобки через запятую. В данном примере эти параметры устанавливают размер шрифта ( 12pt ) и размер страницы ( letterpaper ). Конечно же, для шрифта можно установить и другие размеры ( 9pt , 11pt , 12pt ), но если размер не задан, то предустановленным значением будет 10pt . Что же касается размера страницы, то для него доступны варианты a4paper и legalpaper . Подробнее об этом можете почитать в статье Page size and margins.

Эта команда задает кодировку документа. Ее можно опустить либо изменить на другой вариант, но рекомендуется использовать именно utf-8. Если вам не требуется конкретно другая кодировка, либо вы просто не уверены, то добавьте эту строку во вступление.

Добавление заголовка, автора и даты

Для добавления в документ заголовка, автора и даты необходимо внести во вступление три строки (только не в основное тело документа):

Здесь размещается имя автора. При желании можно также добавить в фигурные скобки следующую команду:

Она может идти после имени автора, внутри скобок команды author . Эта команда добавляет верхний индекс и сноску с текстом из скобок. Очень полезный элемент, если вам нужно поблагодарить в своей статье какую-либо организацию.

Дату можно ввести вручную или использовать команду \today , чтобы она обновлялась автоматически при компиляции документа.

После добавления перечисленных строк преамбула должна выглядеть так:

Теперь, когда вы присвоили документу заголовок, автора и дату, можно вывести в нем эту информацию с помощью команды \maketitle . Ее нужно включить в ту часть тела документа, где вы хотите видеть заголовок.

Добавление комментариев

Как и в случае с любым кодом, зачастую будет нелишним добавлять комментарии. Комментарии – это включаемые в документ текстовые элементы, которые в итоге не отображаются и никак не него не влияют. Они помогают организовывать работу, делать пометки или закомментировать (отключать) строки/разделы при отладке. Чтобы создать комментарий в LaTeX, просто наберите символ % в начале строки, как показано ниже:

Жирный, курсив и подчеркивание

  • Жирный текст в LaTeX пишется внутри команды \textbf <. >;
  • Курсив пишется с помощью команды \textit <. >;
  • Подчеркнутый текст оформляется с помощью команды \underline <. >.

А вот еще одна очень простая команда: \emph <. >. Выполняемые ей для аргумента действия определяются контекстом – внутри обычного текста его выделенная часть переводится в курсив, а при использовании команды в курсивном тексте происходит обратное.

Более того, некоторые пакеты, например Beamer, изменяют поведение команды \emph .

Добавление изображений

В Overleaf для добавления изображений их сначала нужно будет загрузить.

LaTeX не способен обрабатывать изображения самостоятельно, поэтому приходится использовать сторонний пакет. С помощью пакетов можно измерять предустановленный вид документа LaTeX и совершать другие действия. В данном случае нам нужно добавить в документ изображение, для чего потребуется библиотека graphicx , которая привнесет новые команды: \includegraphics <. >и \graphicspath <. >. Для использования graphicx включите во вступление следующую строку: \usepackage .

Команда \graphicspath < > сообщает LaTeX, что изображения находятся в каталоге images в текущей директории.

Команда \includegraphics , в свою очередь, уже конкретно добавляет изображение в документ. Здесь universe представляет имя файла, содержащего изображение, без его расширения, поэтому universe.png стал просто universe . Имя файла изображения не должно содержать пробелов и многоточий.

Примечание: расширение файла включить можно, но лучше его опустить. В этом случае LaTeX будет искать все поддерживаемые форматы. Также при загрузке файлов обычно рекомендуется указывать расширение в нижнем регистре.

Подписи, метки и ссылки

С помощью окружения figure изображения можно подписывать, размечать, а также делать на них ссылки:

В примере выше показаны три важные команды:

Примечание: если вы используете подписи и ссылки на собственном компьютере, то вам потребуется скомпилировать документ дважды, чтобы они сработали. Overleaf делает это автоматически.

Создание списков

Списки в LaTeX создаются очень просто. Делается это с помощью различных окружений списков. Окружения – это разделы, которые требуется представить отличным от остальной части документа образом. Начинаются они с \begin <. >, а завершаются на \end <. >.

Существует два основных типа списков: упорядоченные и неупорядоченные. Каждый из них реализуется в собственном окружении.

Неупорядоченные списки

Неупорядоченные списки создаются пространством itemize. Каждая запись должна предваряться управляющей последовательностью \item , как показано ниже:

По умолчанию отдельные записи обозначаются черной точкой, или буллетом. Текст в записях может иметь неограниченную длину.

Упорядоченные списки

Для упорядоченных списков используется тот же синтаксис, но в другом окружении. В данном случае этим окружением выступает enumerate :

Аналогично неупорядоченным спискам, каждая запись должна предваряться управляющей последовательностью \item , которая будет автоматически генерировать число, отмечая им элемент. Метки перечисления состоят из последовательных чисел, начинающихся с единицы.

Добавление математических выражений

Одно из главных удобств LaTeX состоит в простоте использования математических выражений. Этот инструмент предоставляет два режима их написания: режим inline (встраивание) и режим display (отображение). Первый используется для написания формул, являющихся частью текста. Второй позволяет создавать выражения, не входящие в состав текста или абзаца, а размещаемые на отдельных строках. Вот пример режима встраивания:

Для размещения уравнений в режиме встраивания используйте один из следующих разграничителей: \( . \) , $ . $ или \begin . \end . Работают они равнозначно, поэтому выбор определяется лишь собственным предпочтением.

Режим отображения предлагает два варианта: без нумерации и с нумерацией.

Для вывода уравнений в режиме отображения используйте один из следующих разграничителей: \[ . \] , \begin . \end или \begin . \end . Применять $$ . $$ нежелательно, так как он может внести несогласованные интервалы, а также коряво работать с некотороми математическими пакетами.

Важно: окружение equation* предоставляется в виде стороннего пакета. Подробнее об этом рекомендую почитать статью по amsmath.

Для использования многих команд при работе с математикой необходим пакет amsmath, поэтому не забудьте его добавить. Ниже показан пример некоторых его базовых команд:

Возможности использования математики в LaTeX безграничны, и перечислить их все здесь просто нереально. Так что рекомендую дополнительно почитать соответствующие материалы по теме:

    (Математические выражения) (Сноски и индексы) (Скобки и кавычки) (Дроби и многочлены) (Выравнивание уравнений) (Операторы) (Интервалы в математическом режиме) (Интегралы, суммы и пределы) (Стиль отображения в математическом режиме) (Список греческих букв и математических символов) (Математические шрифты)

Базовое форматирование

Теперь разберем написание аннотаций, а также форматирование документов LaTeX в разных главах, разделах и абзацах.

Аннотации

В научных трудах принято включать краткий обзор основной темы работы. В LaTeX для этого есть специальное окружение abstract . Это окружение помещает текст в специальном формате в начало документа.

Абзацы и перевод строки

Когда при написании документа вам требуется начать новый абзац, нужно дважды нажать «Ввод», вставив таким образом двойную пустую строку. Имейте ввиду, что отступ абзацев LaTeX делает автоматически.

Чтобы создать новую строку без создания очередного абзаца нужно вставить точку разрыва строки, для чего используется \\ (двойной обратный слэш, как в примере) или команда \newline.
При этом не следует использовать несколько \\ или \newline для «имитации» абзацев с увеличенными интервалами между ними, так как это приведет к конфликту с внутренними алгоритмами LaTeX. Для подобного эффекта рекомендуется использовать двойные пустые строки, после чего добавлять во вступление \usepackage .

Дополнительную информацию по теме можно найти в статье Paragraphs and new lines.

Главы и разделы

Команды для организации документа варьируются в зависимости от его типа. Простейшей формой организации выступает деление на разделы, доступное во всех форматах.

Команда \section<> отмечает начало нового раздела, а внутри скобок содержит его имя. Нумерация разделов происходит автоматически и может быть отключена добавлением символа * в команду создания раздела: \section*<> . Можно также использовать подразделы, \subsection<> и даже подподразделы, \subsubsection<> . Ниже перечислены основные уровни вложенности:

Обратите внимание, что \part и \chapter доступны только в классах report и book .

Более подробный разбор структуры документа описан в статье Sections and Chapters.

Создание таблиц

Простые таблицы

Вот простейший пример создания таблицы:

По умолчанию для создания таблиц в LaTeX используется окружение tabular . В этом окружении нужно указывать параметр, в нашем случае . В таком виде он сообщит LaTeX, что в таблице будет три столбца, и текст внутри этих столбцов нужно разместить по центру. Можно также использовать r для выравнивания текста по правому краю и l для выравнивания по левому.

Для указания разрывов в записях таблицы используется символ & . Количество символов выравнивания в каждой строке всегда должно быть на один меньше, чем количество столбцов. Чтобы перейти к очередной строке таблицы используется команда создания новой строки, \\ . Всю таблицу мы заключаем в окружение center , чтобы она размещалась по центру страницы.

Добавление границ

Окружение tabular достаточно гибкое и позволяет размещать разделяющие строки между каждым столбцом.

Границы можно добавлять при помощи команды рисования горизонтальной линии \hline и параметра рисования вертикальной линии | .

  • < |c|c|c| >: эта команда объявляет, что в таблице будут использованы три столбца, разделенные вертикальными линиями. На необходимость вертикального разделения указывает символ |.
  • \hline : эта команда вставит горизонтальную линию. В примере выше горизонтальными линиями мы ограничили верх и низ таблицы, но при желании ими можно разделить ее всю.

Порой создание таблиц в LaTeX вызывает затруднения, поэтому вам может потребоваться обратиться к онлайн-инструменту TablesGenerator.com, чтобы экспортировать код LaTeX для окружения tabular . Копировать и вставлять данные из приложений электронных таблиц можно через опцию FilePaste table data.

Подписи, метки и ссылки

Как и изображения, таблицы можно пописывать и делать на них ссылки. Единственное отличие – это использование вместо figure окружения table .

Примечание: если вы используете подписи и ссылки на своем компьютере, то для работоспособности ссылок нужно будет скомпилировать документ дважды. Overleaf делает это автоматически.

Добавление содержания

Процесс создания содержания очень прост и реализуется командой \tableofcontents :

Разделы, подразделы и главы включаются в содержание автоматически. Чтобы добавить записи вручную, например для указания непронумерованного раздела, используйте команду \addcontentsline , как показано в примере.

Скачивание готового документа

Завершенный документ в формате PDF можно скачать через расположенное слева меню, кликнув PDF.

Есть и более быстрый способ через нажатие кнопки Download PDF в окне просмотра PDF, как показано ниже:

How to change font size on part of the page in LaTeX?

I would like to change the text size for some page part, e.g. for a verbatim block:

janw's user avatar

5 Answers 5

\Large can be obviously substituted by one of:

If you need arbitrary font sizes:

The use of the package \usepackage allows the definition of the fontsize argument inside Verbatim:

The fontsize that you can specify are the common

Aziz Alto's user avatar

To add exact fontsize you can use following. Worked for me since in my case predefined ranges (Large, tiny) are not match with the font size required to me.

Madura Pradeep's user avatar

use \alltt environment instead. Then set size using the same commands as outside verbatim environment.

    The Overflow Blog
Linked
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.8.29.43607

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *