Set text over a scanned document in itext - image

I've made a lot of research on this subject but everything I find is everytime "use the function getOverContent of the stamper". I made this and it still not working.
I made a programm which merge together the PDFs of a repertory, than it paginates this new document (I hope you can follow what I'm writting). The original PDFs are self made (direct saved in PDF) or not (scanned). That's with these last ones where there are trouble. The pagination shows on the firsts but not on the seconds (it exists probably, but it should be behind the image)!
Here is the code for the pagination, has someone THE idea, where I'm mistaken?
PdfReader reader = new PdfReader(source);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destination));
for (int i = start + 1; i <= reader.getNumberOfPages(); i++) {
Phrase noPage = new Phrase((i - start) + "", new Font(FontFamily.COURIER, 14));
float x = reader.getPageSize(i).getRight(20);
float y = reader.getPageSize(i).getTop(20);
PdfContentByte content = stamper.getOverContent(i);
content.beginText();
ColumnText.showTextAligned(content,Element.ALIGN_CENTER, noPage, x, y, 0);
content.endText();
}
stamper.close();
reader.close();
Thanks
After Answer from Bruno, I've made the following:
PdfReader reader = new PdfReader(source);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destination));
for (int i = start + 1; i <= reader.getNumberOfPages(); i++) {
Phrase noPage = new Phrase((i - start) + "", new Font(FontFamily.COURIER, 14));
float x = reader.getCropBox(i).getRight(20);
float y = reader.getCropBox(i).getTop(20);
PdfContentByte content = stamper.getOverContent(i);
ColumnText.showTextAligned(content,Element.ALIGN_CENTER, noPage, x, y, 0);
}
stamper.close();
reader.close();
But it's still not working
For examples: https://www.transfernow.net/24axn1g4wq4l

The original PDFs are self made (direct saved in PDF) or not (scanned). That's with these last ones where there are trouble. The pagination shows on the firsts but not on the seconds (it exists probably, but it should be behind the image)!
The problem is not that the second type of PDFs is scanned but that it uses page rotation.
When a page is rotated, iText inserts a coordinate system rotation instruction at the start of the undercontent and overcontent which ensures that any text drawn without further transformation is displayed upright on the rotated page.
This rotation of the coordinate system obviously needs to be considered when choosing absolute coordinates.
Thus, instead of
reader.getPageSize(i)
you should use
reader.getPageSizeWithRotation(i)
Alternatively you can switch of this iText mechanism using
stamper.setRotateContents(false);
and then consider the presence of page rotation explicitly in all your following operations.

Related

AS3 Particle Explosion Crash

Hellooooo, hope y'all are doing great.
A while ago, I asked a question about how to do particle explosions in AS3 when I was coming from AS2. Luckily, I got help from Organis (thank you so much btw), but every time I try export the animation in SWF, it keeps crashing my file and I'm not sure why?
I should probably preface that what I'm doing is specifically for animation. I'm not trying to make a game, just a simple script where the movieclip I created can explode into different objects in its timeline...if that made any sense.
In case anyone needs the actual file itself, you can download it right here: https://sta.sh/018lqswjfmp2
Here is the AS2 version in case anyone needs it: https://sta.sh/02fzsqon3ohw
Here is the code given to me by Organis:
// Allows the script to interact with the Particle class.
import Particle;
// Number of particles.
var maxparticles:int = 200;
// I imagine you will need to access the particles somehow
// in order to manipulate them, you'd better put them into
// an Array to do so rather then address them by their names.
var Plist:Array = new Array;
// Counter, for "while" loop.
var i:int = 0;
// The loop.
while (i < maxparticles)
{
// Let's create a new particle.
// That's how it is done in AS3.
var P:Particle = new Particle;
// The unique name for the new particle. Whatever you want it for.
P.name = "particle" + i;
// Enlist the newly created particle.
Plist.push(P);
// At the moment, the P exists but is not yet attached to the display list
// (or to anything). It's a new concept, there wasn't such thing in AS2.
// Let's make it a part of the display list so that we can see it.
addChild(P);
i++;
}
And in case anyone needs it, here is the code I used for AS2:
maxparticles = 200; //number of particles
i = 0; //counter, for "while" loop
while(i < maxparticles){
newparticlename = "particle" + i; //creates a new name for a new particle instance
particle.duplicateMovieClip(newparticlename, i); //duplicates our particle mc
i++;
}

pdfbox - rotation issue

As part of a project I am realizing, there are given pdfdocuments which include forms as JPEG Images within A4 pages inside this documents. If have to extract those JPGs out of the PDF. Later on those JPGs are used to build PDF Documents again.
When I simply open up those Documents with any PDFViewer they seem to have no rotation at all, at least it is not visible. So like this icon the have vertical format.
but when I use this sample code to extract the images :
PDDocument doc = PDDocument.load("/path/to/file);
List pages = doc.getDocumentCatalog().getAllPages();
Iterator iter = pages.iterator();
int i = 0;
while (iter.hasNext()) {
PDPage page = (PDPage) iter.next();
System.out.println(page.getRotation());
System.out.println("ROTATION = " + page.getRotation());;
PDResources resources = page.getResources();
Map pageImages = resources.getXObjects();
if (pageImages != null) {
Iterator imageIter = pageImages.keySet().iterator();
while (imageIter.hasNext()) {
String key = (String) imageIter.next();
if(((PDXObjectImage) pageImages.get(key)) instanceof PDXObjectImage){
PDXObjectImage image = (PDXObjectImage) pageImages.get(key);
image.write2file("/path/to/file" + i);
}
i ++;
}
}
}
all extracted JPGs are horizontal format. Further the sysout on the page.rotation tells me that the rotation is set to 270°.
How is that possible? 270 is set, but the PDF is shown vertical (I am no expert on PDF). I even did page.setRotate(0) before extracting the JPGs, but the images still remain horizontally. I read the following Thread telling how to rotate images before drawing them on the pdf. But i need to rotate them before writing them on the filesystem. What is the best way to achieve that?
Unfortunately, I can not attach any of the documents since they are confidential.

Java JLabel.getLocation() always returning 0

I'm studying Java so I'm pretty new.
I'm creating a simple 'maze' type game using GUI layouts, images, labels ect..
To create my maze layouts I used an array of strings;
mazeLayout[0] = "WWWWWWWWWW";
mazeLayout[1] = "WSSSWWSWWW";
mazeLayout[2] = "WSWSWWSSSW";
mazeLayout[3] = "WSWSWWWWSW";
mazeLayout[4] = "WSWSWWWWSW";
mazeLayout[5] = "WSWSWSSSSW";
mazeLayout[6] = "WSWSWSWWWW";
mazeLayout[7] = "WSWSWSWWWW";
mazeLayout[8] = "WSWSSSWWWW";
mazeLayout[9] = "WWWWWWWWWW";
and then converted this into a 2d array and placed a label with in image icon in it depending on the string being 'W' for wall or 'S' for space. Also the labels are an array, my thoughts behind this was for restricting movement of the player so they can't walk though walls.
int mw = 0;
int mf = 0;
for(int y = 0; y < 10; y++){
for(int x = 0; x < 10; x++){
mazeLayout2d[y][x] = mazeLayout[y].substring(x, x+1);
if (mazeLayout2d[y][x].equals("W")){
lblmazewall[mw] = new JLabel();
mazewall = new ImageIcon("mazewall.png");
lblmazewall[mw].setIcon(mazewall);
pCenter.add(lblmazewall[mw]);
mw++;
pCenter.revalidate();
}
if (mazeLayout2d[y][x].equals("S")){
lblmazefloor[mf] = new JLabel();
mazefloor = new ImageIcon("mazefloor.png");
lblmazefloor[mf].setIcon(mazefloor);
pCenter.add(lblmazefloor[mf]);
mf++;
pCenter.revalidate();
}
}
}
My problem is when i run this line
System.out.println(lblmazewall[x].getLocation()); //x being any number
I always get java.awt.Point[x=0,y=0]
I would like to know how to get the location of each wall label so i can check it against my player movement.
Is this even a valid way to do something like this?
Could someone teach me a more efficient way?
Sorry for my crude snippets and or bad programming
Thankyou Niall.
public Point getLocation()
Due to the asynchronous nature of native event handling, this method can return outdated values (for instance, after several calls of setLocation() in rapid succession). For this reason, the recommended method of obtaining a component's position is within java.awt.event.ComponentListener.componentMoved(), which is called after the operating system has finished moving the component.
The layout might not have used setLocation() internally. So that getLocation() does not return the value as expected.

Actionscript 2: Event Cue Points: findNearestCuePoint

Hello everyone and anyone!
Ok... I have been banging my head against the wall with this issue for literally weeks, but I still cannot find an answer that has successfully resolved the issue.
I created an FLA and placed a FLV component with the instance name of videoPlay on the stage.
videoPlay is pathed to a streaming FLV with embedded event cue points. The cue points are numbered sequentially from narration1 to narration16.
I established a listener object:
var videoPlayCuePointListener:Object = new Object();
The event listener for the cue points:
videoPlayCuePointListener.cuePoint = function(eventObject:Object):Void{
if(eventObject.info.name == "narration1"){_root.cc_box.cc_txt.htmlText = cueTxt1);}
else if(eventObject.info.name == "narration2"){_root.cc_box.cc_txt.htmlText = cueTxt2);}
etc, through narration16 }
and so on through narration16.
Then I attached the event listener to the FLV component on stage:
videoPlay.addEventListener("cuePoint", videoPlayCuePointListener);
All of this works very well. As the FLV plays, each event cue point fires off the correct text to the cc_txt dynamic text box.
The issue I am having is that I cannot find the nearest cue point to the FLV playhead so that I can fire events when the user scrubs the timeline.
I have researched this as thoroughly as I possibly could before finally deciding to post the issue, but although the documentation and various postings regarding findNearestCuePoint discovered throughout the web have provided numerous examples, not a single one has been successful.
I have attempted to add a listener to videoPlay that creates an object (nearestCue) and gives nearestCue the value of videoPlay.findNearestCuePoint(videoPlay.playheadTime), then read out nearestCue's name, label, etc. No dice.
Nothing suggested in any posts I have reviewed (many, many posts) has provided an answer.
This seems like it would be the easiest thing to accomplish but I have not been successful a single time.
Any suggestions or assistance would be much appreciated.
Thank you for your time!
Haven't touched AS2 in a long time. I've done a basic test and findNearestCuePoint worked. You're using the FLVPlayback component, right ?
Here's what I've tried:
videoPlayer.autoPlay = false;
onEnterFrame = function():Void{
videoPlayer.seekPercent(_xmouse/Stage.width * 100);
videoPlayer.play();
trace(videoPlayer.findNearestCuePoint(videoPlayer.playheadTime).name);
}
The recommended way would be to find the nearest cue point in an playheadUpdate handler which is triggered after the playhead changes it's value. (e.g. 1. tell the playhead to move, 2. the playhead actually changes the value, 3. the playheadUpdate gets called)
Here's a more basic approach:
onEnterFrame = function():Void{
if(videoPlayer.metadata) trace(videoPlayer.findNearestCuePoint(_xmouse/Stage.width * videoPlayer.metadata.duration).name);
}
In my test I've added 4 cue points. Tried them all: actionscript/event/navigation.
The strange thing was when I tried to access the cuePoints property through videoPlayer
or through videoPlayer.metadata I got an array of 8 undefined objects, and the length of the array was 4 when I traced it. Don't know what the issue is, maybe encoding/codec and as2 compatibility, not sure.
Anyway...as long as you've got your cuePoints array, you can manually find the closest one by looping though all of them and getting the smallest absolute difference between each cue point time and the current time:
function getClosestCuePoint(cuePoints:Array,time:Number):Object{
var numCuePoints:Number = cuePoints.length;
var minDist:Number = 100000000,result:Object;
for(var i:Number = 0 ; i < numCuePoints ; i++){
if(Math.abs(cuePoints[i].time - time) < minDist){
minDist = Math.abs(cuePoints[i].time - time);
result = cuePoints[i];
}
}
return result;
}
Here's a mockup example: let's pretend some boxes on the screen are the cue points and the _xmouse position would be the playhead time. Try this in a new document:
//fake cue points
var numCuePoints:Number = 5;
var cuePoints = [];
for(var i:Number = 0 ; i < numCuePoints ; i++) cuePoints[i] = {name:'narration ' + (i+1),time: 10 + (80 + Math.random() * 20) * i}
//visual hint - separated from the cue points
for(var i:Number = 0 ; i < numCuePoints ; i++) drawBox(this,0x009900,10,15,cuePoints[i].time,Stage.width * .5);
var playhead:TextField = drawText(this,'playhead');
//playhead update
onEnterFrame = function():Void{
playhead._x = _xmouse;
playhead.setTextFormat(new TextFormat('Verdana',11));
playhead.text = 'time: ' + _xmouse+' / cue ' + getClosestCuePoint(cuePoints,_xmouse).name;
}
//find the shortest marker within the shortest distance from the current value
function getClosestCuePoint(cuePoints:Array,time:Number):Object{
var numCuePoints:Number = cuePoints.length;
var minDist:Number = 100000000,result:Object;
for(var i:Number = 0 ; i < numCuePoints ; i++){
if(Math.abs(cuePoints[i].time - time) < minDist){
minDist = Math.abs(cuePoints[i].time - time);
result = cuePoints[i];
}
}
return result;
}
//utils
function drawBox(target:MovieClip,color:Number,width:Number,height:Number,x:Number,y:Number):Void{
target.lineStyle(3,color);
target.moveTo(x,y);
target.lineTo(x+width,y);
target.lineTo(x+width,y+height);
target.lineTo(x,y+height);
target.lineTo(x,y);
}
function drawText(target:MovieClip,name:String):TextField{
var result:TextField = target.createTextField(name,target.getNextHighestDepth(),0,Stage.width * .5-20,100,20);
result.autoSize = 'left';
result.border = true;
result.selectable = false;
return result;
}
HTH
George,
I believe I discovered the issue, and I think it was something that you covered in your previous post, but I glossed over it by accident.
The F4V I was working with had the cue points embedded using Adobe Media Encoder... and that was the entire issue.
I went back and exported the cue points out to XML, then stripped them out of the F4V and re-encoded it without them. Then I edited the XML to change all of the event cue point to actionscript and imported them into the FLA file using the FLV component properties dialogue.
Presto, amazingly enough, I had no issues finding the cue points, tracing them, and using them for any purpose.
So in the future, I just need to remember to set up the cue points in the Properties dialogue and set them to actionscript and I should be golden. So far, it has worked flawlessly with all of the F4V files since making the change.
Thank you very much for your detailed response and your follow up!

Adding text to existing pdf which is closed using itextsharp

Hi
I am creating PDF using itextsharp. Now my requirement is to add more text to the existing pdf. Is it possible if so then how can I do that?
Thanks Dipa
Yes, with certain limitations.
It is difficult, but not impossible, to determine what is already on an existing page.
If all you want to do is add "page X of Y" to the bottom left corner of all your pages, that's easy.
PdfReader reader = new PdfReader( inPath );
PdfStamper stamper = new PdfStamper( reader, new FileOutputStream( outPath ) );
BaseFont font = BaseFont.createFont(); // Helvetica, WinAnsiEncoding
for (int i = 0; i < reader.getNumberOfPages(); ++i) {
PdfContentByte overContent = stamper.getOverContent( i + 1 );
overContent.saveState();
overContent.beginText();
overContent.setFontAndSize( font, 10.0f );
overContent.setTextMatrix( xLoc, yLoc );
overContent.showText( "Page " + (i + 1) + " of " + reader.getNumberOfPages() );
overContent.endText();
overContent.restoreState();
}
stamper.close();
A big watermark isn't much more difficult. Adding things to a PDF at one or more predetermined locations is quite doable.
At the other end of the spectrum is "change text within existing paragraphs and reflow them". That's all but impossible. It would be much easier to rebuild the original PDF with the new data.
In fact, if at all possible, just rebuild them. You did it once, do it again.

Resources