iText加入页码

如果不需要显示总页数(像X of Y , 当前是第X页,共Y页之类的),下面的方法就够.

在Document.open()之前加上

HeaderFooter footer = new HeaderFooter(new Phrase("页码:",yourFont, true);
footer.setBorder(Rectangle.NO_BORDER);
document.setFooter(footer);


如果要加上总页数,就麻烦多了-___-.

您需要使用PdfTemplate来保存总页数信息,需要使用PdfPageEvent来在一些类型的事件响应代码里做些处理.

获得总页数这样的工作随便一想好像很容易,但是在iText流水式输出内容到pdf文档中的每一页的时候,它怎么知道一共有多少页?好吧,是在它把内容全部输出完的时候,它知道自己弄了多少页了,但这时候又怎么回过头来给每个页面重新加上页码?

说实话,到现在我也只是根据[url=http://itextdocs.lowagie.com/tutorial/directcontent/pageevents/index.php]官方例子[/url]成功得到了想要的效果而并不太了解相关的工作原理.

我们可以通过实现PdfPageEvent接口或者扩展PdfPageEventHelper类,使我们可以在文档开始、每页开始、每页结束、文档结束等地方做些工作以达到插入页码的目的.


public class PDFMaker extends PdfPageEventHelper {


/**这个PdfTemplate实例用于保存总页数 */
public PdfTemplate tpl;
/** 页码字体 */
public BaseFont helv;

public void make(Document doc) throws Exception
{

pdf = new com.lowagie.text.Document(pagesize,10,10,10,10);
PdfWriter writer = PdfWriter.getInstance(pdf,pdfout);

//设置页页事件监听器
Font pageNumFont = new Font(bf_chn,9,Font.NORMAL);
writer.setPageEvent(this);

pdf.open();

//正常的PDF写入操作代码

pdf.close();

}

@Override
public void onCloseDocument(PdfWriter writer, com.lowagie.text.Document arg1) {
// TODO Auto-generated method stub
System.out.println("OCD");
tpl.beginText();
tpl.setFontAndSize(helv, 12);
tpl.setTextMatrix(0, 0);
tpl.showText("" + (writer.getPageNumber() - 1));
tpl.endText();
}


/* (non-Javadoc)
* @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
*/
@Override
public void onEndPage(PdfWriter writer, com.lowagie.text.Document document) {
// TODO Auto-generated method stub
System.out.println("OEP");
PdfContentByte cb = writer.getDirectContent();
cb.saveState();

String text = "Page " + writer.getPageNumber() + " of ";
float textSize = helv.getWidthPoint(text, 9);
float textBase = document.bottom();
cb.beginText();
cb.setFontAndSize(helv, 9);
// for odd pagenumbers, show t

cb.setTextMatrix(document.left(), textBase);
cb.showText(text);
cb.endText();
cb.addTemplate(tpl, document.left() + textSize, textBase);
cb.saveState();
}


/* (non-Javadoc)
* @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
*/
@Override
public void onOpenDocument(PdfWriter writer, com.lowagie.text.Document arg1) {
// TODO Auto-generated method stub
System.out.println("OOD");
try{
// initialization of the template
tpl = writer.getDirectContent().createTemplate(100, 100);

// tpl.setBoundingBox(new Rectangle(0, 0, 10, 10));
// initialization of the font
helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
}catch(Exception e)
{

}
}

}






基本流程如上述不完整程序(要完整的请看官方例子,不过那个例子还有其他演示功能不好集中精神分析页码问题),我不明白的是,总页码数是在文档结束时放进PdfTemplate实例里面,怎么在文档结束前的每一页结尾处都可以拿到该值?

之前在每页结尾处的PdfTemplate实例调用结果类似于插入一个占位符,文档总页数确定了的进候再回去填值?
Java 使用iText7生成带页码的PDF文件(同时生成目录,但是不会合并两个PDF) gradle项目,首次使用请先下载jar包(右键项目→Gradle→Refresh),不然报错! 立即下载

相关推荐

iText7 html转换为pdf生成页码、页眉、页脚DEMO

itext7 html转换为pdf;iText7页码、页眉、页脚,itext 的复杂表格实现;完整springboot项目代码

iText5添加页眉、页脚,logo、页码等实现

iText5添加页眉、页脚,logo、页码

running17的博客 6499

第四篇:关于python程序打包的问题-找不到fsspec

这个问题困扰了我将近两天的时间一直找不到什么好的办法,甚至打算放弃。主要原因是身边没有可以述说的人,也没有可以请教的人。正在想要放弃的时候找到了解决办法。 打包后运行程序是这样的, 大概意思是找不见fsspec这个依赖,刚接触python说实话对于这些第三方库理解不是很到位,我的理解就是:类似于java程序中的jar包,程序找不见了。可怎么让他找见了,刚开始以为我自己没有安装fsspec,在cmd中进行了安装,结果如下图所示 很明显,已经安装并且安装目录都有,跟着网上的一些解决办法,在打包的时候把这.

weixin_47861710的博客 5870

itext生成pdf加页码和总页码

原生成pdf代码(不带页码) public static void html2pdf(String htmlFile, String pdfFile) { // step 1 String url; OutputStream os = null; try { File file = new File(p...

qi923701的博客 1万+

NVIDIA DGX Spark实战:如何在桌面上轻松运行200B参数大模型(附配置教程)

本文提供了NVIDIA DGX Spark在桌面端运行200B参数大模型的完整实战指南。详细介绍了从硬件初始化、系统配置、容器化环境搭建,到模型加载、量化、推理流水线编写及性能调优的全过程。重点阐述了如何利用其统一内存架构和TensorRT-LLM等工具进行高效本地推理,并探讨了通过双机互联扩展以应对超大规模模型的方法。

i3j4k5的博客 799

【测开求职】面试题:JAVA 吐血整理

本篇文章包含本次测开工程师秋招过程中遇到的所有JAVA面试题,全文两万字,亲测应对各个大厂的面试毫无压力👉

vector的博客 1218

itext设置页码(第x页/第y页)

1.新建类ItextPdfHeaderFooter import com.itextpdf.text.Document; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.PageSize; import com.itextpdf.text.Phrase; import...

落叶的位置 1864

实战指南:理解 ThreadLocal 原理并用于Java 多线程上下文管理

探讨如何基于实现一个高效的上下文管理组件,以解决多线程环境下的数据共享和上下文管理这些问题。通过具体的代码示例和实战展示如何为多线程编程提供一种简洁而高效的上下文管理方案。

曾经“等你生日那天”都遥远得像未来,如今却可欢愉的挥手说“下个十年见” 11万+

itext7生成pdf页脚页码

itext7生成pdf页脚页码

程序员二胖 2034

流媒体服务软件-LiveNVR channeltree 未授权访问

LiveNVR 能够通过简单的网络摄像机通道配置,将传统监控行业里面的高清网络摄像机 IPCamera、NVR 等具有 RTSP/Onvif 协议输出的设备接入到 LiveNVR,LiveNVR 能够将这些设备源的音/视频数据进行采集、转换、输出,进行全平台终端直播(PC、Android、iOS、微信、H5),并且LiveNVR能够将视频源的直播数据对接到第三方 CDN 网络,实现安防设备互联网级别的直播分发。对channeltree接口加上权限校验。直接访问接口即可获取数据。

iSee857的博客 1047

基于YOLOv8/YOLOv7/YOLOv6/YOLOv5的水果识别系统(Python+PySide6界面+训练代码)

本文详细介绍了基于YOLO系列目标检测算法(包括YOLOv5、YOLOv6、YOLOv7和YOLOv8)的水果识别系统的设计与实现。系统采用Python语言开发,结合PySide6构建用户界面,实现了从数据准备、模型训练到部署应用的全流程。本文将提供完整的代码实现、详细的训练过程分析以及性能对比实验,并给出推荐的数据集资源。该系统可以准确识别多种水果类型,为智能农业、自动售货、食品加工等领域提供技术支持。

YOLO 568

iText系列(四) iText加入页码

如果不需要显示总页数(像X of Y , 当前是第X页,共Y页之类的),下面的方法就够. 在Document.open()之前加上 Java代码 HeaderFooterfooter=newHeaderFooter(newPhrase("页码:",yourFont,true); footer.setBorder(Rectangle.NO_BORDER);

jarniyy的博客 1万+

C# 量子级跨平台开发:用Uno Platform实现Windows、iOS、Android的“量子纠缠”UI同步

墨瑾轩推出编程学习平台,通过XAML的“量子纠缠”技术,实现跨平台开发的高效与一致性。传统方案中,多平台代码重复率高,UI差异大,而量子级方案则通过一套代码构建全平台应用,UI原子化同步,开发效率提升5倍。Uno Platform的“量子纠缠”架构解决了代码碎片化、性能瓶颈和调试难题,实现UI原子化同步、性能提升300%和跨平台数据无缝同步。核心架构包括XAML的跨平台渲染、MVVM的量子叠加态架构、平台差异的量子退相干处理以及性能优化的量子隧穿效应,为开发者提供高效、一致的跨平台开发体验。

java专栏 1168

Itext给PDF添加页码

<dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> import com.itextpdf.text.Document;...

finally_flx的博客 4544

CEEMDAN算法及其应用

本博文主要介绍CEEMDAN算法的原理及其在信号去噪方面的应用

总结论文中的算法并给出论文的复现代码 6万+

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

itext 合并 pdf 并插入页码

第一步 引用jar <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13.1</version> ...

z446981439的博客 2707

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

java itext pdf 添加页码

一、页码添加,重写事件,直接上代码: public class PdfPageXofYEventHelper extends PdfPageEventHelper { public PdfTemplate total; public BaseFont baseFont; /** * 重写PdfPageEventHelper中的onOpenDocument方法 ...

a_good_child的博客 2679

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

java pdf添加页码_java itext pdf 怎么加页码

展开全部引用spire.pdf.jar到java程序中32313133353236313431303231363533e59b9ee7ad9431333431366266,然后使用下面的代码,页码的位置可以自己调整importcom.spire.pdf.automaticfields.PdfCompositeField;importcom.spire.pdf.automaticfields.P...

weixin_29205061的博客 787

itext生成pdf(附带页眉,页脚,页码)

package cn.picclife.mwx.salesupport.marketactivity.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import com....

weixin_30955341的博客 2160

java pdf stamper_使用pdfstamper(Itext)将页码添加到pdf

我有这个代码protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ByteArrayOutputStream output = new ByteArrayOutputStream();try{response.setC...

weixin_28695537的博客 2369

ITEXT-定位PDF中图片的坐标与页码

问题场景:用itext自动生成PDF的过程中,想要在PDF中的某一页加入水印,这个水印图片的页码不固定,所以不能直接用‘sealStamperUnder = stamp.getUnderContent(page-1);’方式加入水印。但是该水印在某一固定图片的上一页,那么我们可以定位这张图片的位置信息,以此获取水印图片的页码信息。通过这种方法还可以获得图片的坐标信息。代码需导入的jar包:itext

心有多大舞台就有多大 1万+

使用itextpdf对PDF文件添加页码

说是对PDF添加页码,其实就是将页码印到PDF上,下面的这种方法比较灵活也比较简单,可以对添加页码的内容以及位置进行调整。话不多说,直接上代码。 import com.itextpdf.text.BaseColor; import com.itextpdf.text.Font; import com.itextpdf.text.Rectangle; import com.itextpdf.text...

sinat_42478429的博客 3823

iText 页码、页眉、页脚工具

iText页码,页眉,页脚 DEMO下载及实现:https://download.csdn.net/download/iosweb/10623375 1,页码工具类 package excelPOI; import java.io.IOException; import com.itextpdf.text.Document; import com.itextpdf.text.Doc...

IOS_Mainstay的博客 1379

pdf按照页码分割 java_java使用itext按页码拆分pdf文件

java使用itext按页码拆分pdf文件,代码实现如下:/*** @author viralpatel.net** @param inputStream Input PDF file* @param outputStream Output PDF file* @param fromPage start page from input PDF file* @param toPage end pag...

weixin_29260291的博客 455

绘制pdf表格 (二) 通过itext实现在pdf中绘制excel表格样式设置中文字体、水印、logo、页眉、页码

1、 绘制pdf表格 (二) 通过itext实现在pdf中绘制excel表格样式设置中文字体、水印、logo、页眉、页码

一恍过去 2万+
上一篇: iText生成PDF报表分页表头问题的解决
下一篇: IE6下DIV高度显示的Bug
JavaNoob
博客等级 码龄19年 4粉丝 100原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址