Рубрики
Без рубрики

Вставить верхний и нижний колонтитулы в Word с помощью Java

Верхние и нижние колонтитулы – это разделы, которые отображаются на верхнем / нижнем поле документа Word. Они – это ты… Помеченный java, верхний колонтитул, нижний колонтитул, word.

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

1# Сначала вам нужно импортировать зависимость jar в ваше Java-приложение (2 метода)

● Загрузите бесплатный API ( Бесплатный шпиль. Документ для Java ) и распакуйте его, затем добавьте Spire.Doc.jar файл в ваше Java-приложение в качестве зависимости.

● Непосредственно добавьте зависимость jar в проект maven, добавив следующие конфигурации в pom.xml .


   
      com.e-iceblue
      e-iceblue
      http://repo.e-iceblue.com/nexus/content/groups/public/
   


   
      e-iceblue
      spire.doc.free
      3.9.0
   

2# Соответствующий фрагмент кода вставки верхнего и нижнего колонтитулов в документ Word:

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

public class InsertHeaderAndFooter {

    public static void main(String[] args) {

        //Load a Word document
        Document document = new Document();
        document.loadFromFile("sample0.docx");

        //Get the first section
        Section section = document.getSections().get(0);

        //Call insertHeaderAndFooter method to add header and footer to the section
        insertHeaderAndFooter(section);

        //Save to file
        document.saveToFile("out/HeaderAndFooter.docx", FileFormat.Docx);
    }

    private static void insertHeaderAndFooter(Section section) {

        //Get header and footer from a section
        HeaderFooter header = section.getHeadersFooters().getHeader();
        HeaderFooter footer = section.getHeadersFooters().getFooter();

        //Add a paragraph to header
        Paragraph headerParagraph = header.addParagraph();

        //Insert a picture to header paragraph and set its position
        DocPicture headerPicture = headerParagraph.appendPicture("C:\\Users\\Administrator\\Desktop\\mars.jpg");
        headerPicture.setHorizontalAlignment(ShapeHorizontalAlignment.Left);
        headerPicture.setVerticalOrigin(VerticalOrigin.Top_Margin_Area);
        headerPicture.setVerticalAlignment(ShapeVerticalAlignment.Center);

        //Add text to header paragraph
        TextRange text = headerParagraph.appendText("Introduction of Mars");
        text.getCharacterFormat().setFontName("Arial");
        text.getCharacterFormat().setFontSize(10);
        text.getCharacterFormat().setItalic(true);
        text.getCharacterFormat().setBold(true);
        headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

        //Set text wrapping to behind
        headerPicture.setTextWrappingStyle(TextWrappingStyle.Behind);

        //Set the bottom border style of the header paragraph
        headerParagraph.getFormat().getBorders().getBottom().setBorderType(BorderStyle.Single);
        headerParagraph.getFormat().getBorders().getBottom().setLineWidth(1f);

        //Add a paragraph to footer
        Paragraph footerParagraph = footer.addParagraph();

        //Add Field_Page and Field_Num_Pages fields to the footer paragraph
        footerParagraph.appendField("page number", FieldType.Field_Page);
        footerParagraph.appendText(" of ");
        footerParagraph.appendField("number of pages", FieldType.Field_Num_Pages);
        footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

        //Set the top border style of the footer paragraph
        footerParagraph.getFormat().getBorders().getTop().setBorderType(BorderStyle.Single);
        footerParagraph.getFormat().getBorders().getTop().setLineWidth(1f);
    }
}

3# Сгенерированный документ Word показан как показано ниже:

Оригинал: “https://dev.to/jazzzzz/insert-header-and-footer-to-word-using-java-2lc8”