Номера страниц позволяют читателям легко запомнить, с чего начать в следующий раз. Добавление номеров страниц в документ Word полезно, особенно когда документ довольно большой. В этой статье я покажу вам, как добавить непрерывные номера страниц в документ Word, содержащий несколько разделов, и как добавить разные номера страниц в разные разделы с помощью Spire. Документ для Java .
Установить Spire.Doc.jar
Если вы создаете проект, не относящийся к Maven, загрузите файл jar с эту ссылку и добавьте ее в качестве зависимости в свое приложение. Для проектов Maven вы можете легко добавить jar в свое приложение, используя следующие конфигурации.
com.e-iceblue e-iceblue http://repo.e-iceblue.com/nexus/content/groups/public/ e-iceblue spire.doc 3.8.1
Добавьте непрерывные номера страниц ко всему документу
По умолчанию, когда мы добавляем номера страниц в верхний или нижний колонтитул первого раздела, другие разделы будут ссылаться на предыдущий раздел, чтобы использовать тот же верхний или нижний колонтитул. Поэтому нам нужно только установить номер страницы в первом разделе.
import com.spire.doc.Document; import com.spire.doc.FieldType; import com.spire.doc.FileFormat; import com.spire.doc.HeaderFooter; import com.spire.doc.documents.HorizontalAlignment; import com.spire.doc.documents.Paragraph; public class ContinuousPaging { public static void main(String[] args) { //Load a Word document Document document = new Document("C:\\Users\\Administrator\\Desktop\\Sections.docx"); //Get the header object of the first section HeaderFooter header = document.getSections().get(0).getHeadersFooters().getHeader(); //Add a paragraph in header Paragraph headerParagraph = header.addParagraph(); //Append text and automatic page field to the paragraph headerParagraph.appendText("Page "); headerParagraph.appendField("currentPage", FieldType.Field_Page); headerParagraph.appendText(" of "); headerParagraph.appendField("pageNum", FieldType.Field_Num_Pages); //Set paragraph alignment to right headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right); //Save to file document.saveToFile("ContinuousNumbering.docx", FileFormat.Docx_2013); } }
Добавьте прерывистые номера страниц в разные разделы
Когда мы устанавливаем разные номера страниц для разных разделов, нам нужно установить другой номер начальной страницы для следующего раздела.
import com.spire.doc.Document; import com.spire.doc.FieldType; import com.spire.doc.FileFormat; import com.spire.doc.HeaderFooter; import com.spire.doc.documents.HorizontalAlignment; import com.spire.doc.documents.Paragraph; public class DiscontinuousNumbering { public static void main(String[] args) { //Load a Word document Document document = new Document("C:\\Users\\Administrator\\Desktop\\Sections.docx"); //Get the header object of the first section HeaderFooter header = document.getSections().get(0).getHeadersFooters().getHeader(); //Add a paragraph in header Paragraph headerParagraph = header.addParagraph(); //Append text and automatic page field to the paragraph headerParagraph .appendText("Page "); headerParagraph .appendField("currentPage", FieldType.Field_Page); headerParagraph .appendText(" Section "); headerParagraph .appendField("sectionNum", FieldType.Field_Section); //Set paragraph alignment to right headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right); //Determine if the document has more than one section if (document.getSections().getCount()>1) { //Loop through the sections except the first one for (int i = 1; i < document.getSections().getCount(); i++) { //Restart page numbering of the next section document.getSections().get(i).getPageSetup().setRestartPageNumbering(true); //Set the starting number to 1 document.getSections().get(i).getPageSetup().setPageStartingNumber(1); } } //Save to file document.saveToFile("DiscontinuousNumbering.docx", FileFormat.Docx_2013); } }
Оригинал: “https://dev.to/eiceblue/add-page-numbers-to-an-existing-word-documnet-in-java-1hc8”