JAVA获取PDF当前页,获取PDF Java Web中的当前页面

I need to read the current page number from my web application. I have:

That open the PDF on page = 5, and the user can navigate to another page. Then, when the user click on a button/link, I need to get the current index of the page in PDF.

My users use Acrobat Reader, and I cannot use plugins that aren't from Adobe. I can use Javascript/Java code.

Thanks

Tami

解决方案

I found out that I can use iText (free software) to Inject JavaScript to the pdf file ,

the JS in the PDF send a message to a container in the html .

the message contain the current page , and it is passed to the container each time the page is changed.

I use pdfobject.js pdfobject.min.js to create the PDFJS object that catch the message .

the code in Java to inject JS to PDF :

public String mAddJS()

{

InputStream vbReaderFile = null;

try

{

vbReaderFile = new FileInputStream("C:\\test.pdf");

PdfReader myReader = new PdfReader( vbReaderFile ); // throws IOException

PdfStamper myStamper = new PdfStamper( myReader, new FileOutputStream("C:\\outTest.pdf") ); // throws IOE, DocumentException

// add a page-open script, 1 is the first page, not zero0

PdfAction jsAction = PdfAction.javaScript ("app.alert('Think again next time!');", myStamper.getWriter());

int pageNum = myReader.getNumberOfPages();

for(int i=1 ; i

{

jsAction = PdfAction.javaScript (

"this.disclosed=true;" +

"if(this.hostContainer){" +

"var names = new Array();names[0]=" + i + ";" +

"try{this.hostContainer.postMessage(names);}" +

"catch(e){app.alert(e.message); }"+

"}", myStamper.getWriter());

myStamper.setPageAction( PdfWriter.PAGE_OPEN, jsAction, i);

}

myStamper.close(); // write everything out, throws DocumentException, IOE

vPath = "C:\\outTest.pdf";

// JavascriptContext.addJavascriptCall(FacesContext.getCurrentInstance(), "mChangePDF('C:\\outTest.pdf');");

}

catch (Exception e) {

e.printStackTrace();

}

return null;

}

the html page :

height="550px" width="650px">

the JS on the html:

var PDF1;

var PDF2;

window.onload = function(evt)

{

createPDF();

createMessageHandler();

}

function createPDF(){

PDF1 = new PDFObject({

url: "test.pdf#page=3",

id: "myPDFObj",

width: "500px",

height: "300px"

});

PDF2 = PDF1.embed("myForm:myDivPdf");

};

function createMessageHandler() {

var PDFObject = document.getElementById("myPDFObj");

if(PDFObject==null)

alert('e1');

PDFObject.messageHandler = {

onMessage: function(msg) {

// alert('app');

alert( msg[0]);

},

onError: function(error, msg) {

alert('error.message');

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值