gpt4 book ai didi

java - PDFBox 中的行编号

转载 作者:行者123 更新时间:2023-12-02 00:18:48 25 4
gpt4 key购买 nike

目前,我评估了一些用 Java 创建 PDF 的库。 PDFBox 目前是我想使用的库之一。在我的用例中,我想给每一章一个新的行编号。我尝试并搜索了很多,但我真的不知道如何实现这一点。有人有一些建议吗?非常感谢您所做的一切!

enter image description here

最佳答案

也许会有帮助。以下是如何生成菜单和子菜单(以及主菜单和子菜单编号):

使用这个类:

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class PdfExample
{
private String pdfFileName = "";

public PdfExample(String pdfFileName)
{
this.pdfFileName=pdfFileName;

//creating new document:
PDDocument document = new PDDocument();
PDPage blancPage = new PDPage();
document.addPage(blancPage);
PDFont font_TIMES_ROMAN = PDType1Font.TIMES_ROMAN;

try
{
PDPageContentStream fileStream = new PDPageContentStream(document,blancPage);
fileStream.setFont( font_TIMES_ROMAN, 12 );

fileStream.beginText();
fileStream.newLineAtOffset(50,735);
fileStream.showText("Chapter numbering example:");
fileStream.endText();

//veeery simple positioning configuration:
int mainMenuPosition_Y = 700;
int mainMenuPosition_X = 50;
int lineSpacing = 30;
int numberOfMainMenus = 6;
int subMenuLeftMargin = mainMenuPosition_X+20;

HashMap<Integer, ArrayList> subMenu = new HashMap<Integer,ArrayList>();
//I'm adding some sample submenu's:
subMenu.put(1,new ArrayList<String>(Arrays.asList("Item 1","Item 2","Item 3"))); // firstOne Main Menu
subMenu.put(2,new ArrayList<String>(Arrays.asList("Item 1","Item 2","Item 3"))); // second Main Menu
subMenu.put(5,new ArrayList<String>(Arrays.asList("Item 1","Item 2"))); // 5th

for(int i = 1 ; i <= numberOfMainMenus ; i++)
{
fileStream.beginText();
fileStream.newLineAtOffset(mainMenuPosition_X,mainMenuPosition_Y);
fileStream.showText(i+". Main Menu");
fileStream.endText();

if(subMenu.get(i)!=null)
{
for(int w = 0; w < subMenu.get(i).size();w++)
{
System.out.println(subMenu.get(i).get(w));
fileStream.beginText();
fileStream.newLineAtOffset(subMenuLeftMargin,(mainMenuPosition_Y-=15));
fileStream.showText(i+"."+(w+1)+" "+subMenu.get(i).get(w));
fileStream.endText();
}
}
mainMenuPosition_Y-=lineSpacing;
}

fileStream.close();
document.save(pdfFileName+".pdf");
document.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}//end
}

然后就:

PdfExample document = new PdfExample("SimpleExample");

此代码将生成如下内容:

SimpleExample

并记住 IDE 中的“项目结构库”:

Project Structure Libraries

希望我能帮上一点忙;]

关于java - PDFBox 中的行编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58081996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com