we are using iText PDFPTable. The problem we are facing is because of the following line of code:
table.setHeaderRows(headerRows);
This piece of code works fine in local environment (WAS hosted in windows), but doesn't work, alignment is messed up, in dev server (WAS hosted in Unix). We are unable to figure out what the problem is, as in both cases IE is used. Can someone please answer why alignment issues come up in dev server?
adding more code...
method creating standard table:
public PdfPTable createStandardTable(int columnCount, int headerRows) {
zebraTable = true;
horizontalBorders = false;
PdfPTableEvent tableEvent = new PdfPTableEvent()
{
// begin (another) anonymous inner class extends PdfPTableEvent
#Override
public void tableLayout(PdfPTable table, float[][] width, float[] height,
int headerRows, int rowStart, PdfContentByte[] canvas) {
// code provided by Bruno Lowagie, author of iText, via StackOverflow.
float widths[] = width[0];
float x1 = widths[0];
float x2 = widths[widths.length - 1];
float y = height[height.length - 1];
PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
cb.moveTo(x1, y);
cb.lineTo(x2, y);
cb.setColorStroke(TABLE_BORDER_COLOR);
cb.stroke();
}
// end anonymous inner class extends PdfPTableEvent
};
PdfPTable table = tableCreationHelper(columnCount, headerRows);
table.setTableEvent(tableEvent);
return table;
}
private helper method
private PdfPTable tableCreationHelper(int columnCount, int headerRows) {
PdfPTable table = new PdfPTable(columnCount);
table.setSpacingBefore(TABLE_SPACING);
table.setSpacingAfter(TABLE_SPACING);
table.setWidthPercentage(TABLE_WIDTH_PERCENT);
table.setHeaderRows(headerRows);
return table;
}
please let me know if you need more information
Thanks much,
Babu.
I figured out the issue. Dev server had iText version 5.5.0, where as local configuration is 5.5.2. setHeadersRow function of iText 5.5.0 messed up the alignment.
Related
I have a pdf which comprises of some data, followed by some whitespace. I don't know how large the data is, but I'd like to trim off the whitespace following the data
PdfReader reader = new PdfReader(PDFLOCATION);
Rectangle rect = new Rectangle(700, 2000);
Document document = new Document(rect);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(SAVELCATION));
document.open();
int n = reader.getNumberOfPages();
PdfImportedPage page;
for (int i = 1; i <= n; i++) {
document.newPage();
page = writer.getImportedPage(reader, i);
Image instance = Image.getInstance(page);
document.add(instance);
}
document.close();
Is there a way to clip/trim the whitespace for each page in the new document?
This PDF contains vector graphics.
I'm usung iTextPDF, but can switch to any Java library (mavenized, Apache license preferred)
As no actual solution has been posted, here some pointers from the accompanying itext-questions mailing list thread:
As you want to merely trim pages, this is not a case of PdfWriter + getImportedPage usage but instead of PdfStamper usage. Your main code using a PdfStamper might look like this:
PdfReader reader = new PdfReader(resourceStream);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("target/test-outputs/test-trimmed-stamper.pdf"));
// Go through all pages
int n = reader.getNumberOfPages();
for (int i = 1; i <= n; i++)
{
Rectangle pageSize = reader.getPageSize(i);
Rectangle rect = getOutputPageSize(pageSize, reader, i);
PdfDictionary page = reader.getPageN(i);
page.put(PdfName.CROPBOX, new PdfArray(new float[]{rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()}));
stamper.markUsed(page);
}
stamper.close();
As you see I also added another argument to your getOutputPageSize method to-be. It is the page number. The amount of white space to trim might differ on different pages after all.
If the source document did not contain vector graphics, you could simply use the iText parser package classes. There even already is a TextMarginFinder based on them. In this case the getOutputPageSize method (with the additional page parameter) could look like this:
private Rectangle getOutputPageSize(Rectangle pageSize, PdfReader reader, int page) throws IOException
{
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
TextMarginFinder finder = parser.processContent(page, new TextMarginFinder());
Rectangle result = new Rectangle(finder.getLlx(), finder.getLly(), finder.getUrx(), finder.getUry());
System.out.printf("Text/bitmap boundary: %f,%f to %f, %f\n", finder.getLlx(), finder.getLly(), finder.getUrx(), finder.getUry());
return result;
}
Using this method with your file test.pdf results in:
As you see the code trims according to text (and bitmap image) content on the page.
To find the bounding box respecting vector graphics, too, you essentially have to do the same but you have to extend the parser framework used here to inform its listeners (the TextMarginFinder essentially is a listener to drawing events sent from the parser framework) about vector graphics operations, too. This is non-trivial, especially if you don't know PDF syntax by heart yet.
If your PDFs to trim are not too generic but can be forced to include some text or bitmap graphics in relevant positions, though, you could use the sample code above (probably with minor changes) anyways.
E.g. if your PDFs always start with text on top and end with text at the bottom, you could change getOutputPageSize to create the result rectangle like this:
Rectangle result = new Rectangle(pageSize.getLeft(), finder.getLly(), pageSize.getRight(), finder.getUry());
This only trims top and bottom empty space:
Depending on your input data pool and requirements this might suffice.
Or you can use some other heuristics depending on your knowledge on the input data. If you know something about the positioning of text (e.g. the heading to always be centered and some other text to always start at the left), you can easily extend the TextMarginFinder to take advantage of this knowledge.
Recent (April 2015, iText 5.5.6-SNAPSHOT) improvements
The current development version, 5.5.6-SNAPSHOT, extends the parser package to also include vector graphics parsing. This allows for an extension of iText's original TextMarginFinder class implementing the new ExtRenderListener methods like this:
#Override
public void modifyPath(PathConstructionRenderInfo renderInfo)
{
List<Vector> points = new ArrayList<Vector>();
if (renderInfo.getOperation() == PathConstructionRenderInfo.RECT)
{
float x = renderInfo.getSegmentData().get(0);
float y = renderInfo.getSegmentData().get(1);
float w = renderInfo.getSegmentData().get(2);
float h = renderInfo.getSegmentData().get(3);
points.add(new Vector(x, y, 1));
points.add(new Vector(x+w, y, 1));
points.add(new Vector(x, y+h, 1));
points.add(new Vector(x+w, y+h, 1));
}
else if (renderInfo.getSegmentData() != null)
{
for (int i = 0; i < renderInfo.getSegmentData().size()-1; i+=2)
{
points.add(new Vector(renderInfo.getSegmentData().get(i), renderInfo.getSegmentData().get(i+1), 1));
}
}
for (Vector point: points)
{
point = point.cross(renderInfo.getCtm());
Rectangle2D.Float pointRectangle = new Rectangle2D.Float(point.get(Vector.I1), point.get(Vector.I2), 0, 0);
if (currentPathRectangle == null)
currentPathRectangle = pointRectangle;
else
currentPathRectangle.add(pointRectangle);
}
}
#Override
public Path renderPath(PathPaintingRenderInfo renderInfo)
{
if (renderInfo.getOperation() != PathPaintingRenderInfo.NO_OP)
{
if (textRectangle == null)
textRectangle = currentPathRectangle;
else
textRectangle.add(currentPathRectangle);
}
currentPathRectangle = null;
return null;
}
#Override
public void clipPath(int rule)
{
}
(Full source: MarginFinder.java)
Using this class to trim the white space results in
which is pretty much what one would hope for.
Beware: The implementation above is far from optimal. It is not even correct as it includes all curve control points which is too much. Furthermore it ignores stuff like line width or wedge types. It actually merely is a proof-of-concept.
All test code is in TestTrimPdfPage.java.
I try draw a A5 rentangle in a PDF with Itext using Rectangle class and Utilities.milimetersToPoints method but when i print the PDF and measure the rectangle the measurments is not the A5 dimensions.
public static boolean createPDF(String pathPDF) {
Document document = new Document(PageSize.A4);
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pathPDF));
writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
document.open();
createRectangle(writer, 30.75f, 11, 148.5f, 210, Color.RED);
document.close();
} catch (Exception e) {
logger.error("Error , e);
return false;
}
return true;
}
private static void createRectangle(PdfWriter writer, float x, float y, float width, float height, Color color) {
float posX = Utilities.millimetersToPoints(x);
float posY = Utilities.millimetersToPoints(y);
float widthX = Utilities.millimetersToPoints(width+x);
float heightY = Utilities.millimetersToPoints(height+y);
Rectangle rect = new Rectangle(posX, posY, widthX, heightY);
PdfContentByte canvas = writer.getDirectContent();
rectangle.setBorder(Rectangle.BOX);
rectangle.setBorderWidth(1);
rectangle.setBorderColor(color);
canvas.rectangle(rectangle);
}
what i'm doing wrong?
I use Itext 2.1.7
Many Thanks
I just ran your SSCCE (Short, Self Contained, Correct (Compilable), Example), and printed the resulting PDF from Adobe Reader. I measured the red rectangle both on-screen using the Adobe Reader measuring tool and on-paper.
The result on screen:
matches your parameters
createRectangle(writer, 30.75f, 11, 148.5f, 210, Color.RED);
------------------------------------^^^^^^--^^^
exactly, and the measurement on-paper matches as exactly as measurement with rulers can be.
Possible causes of the problem on your side:
I use a current iText version. But while there have been quite a lot of improvements and fixes since 2.1.7, I doubt any fixes had been applied here.
Different printers; some printers are known to scale while printing.
Different viewer from which you print; some viewers may always scale.
Different scaling settings in printer dialog.
The exercise is as follows:
Rewrite programming exercise 3 from lecture 6 by
creating a class called Button to replace the arrays.
a) Create the class and define class variables that
hold information about position, dimensions and
color. In addition a class variable should be made,
which contains the title of the particular button.
Use the constructor to set the initial values of the
class variables.
So basically, I have to convert a previous exercise I have done into a class.
This is how I made the previous exercise in case you need it: http://pastebin.com/RqM6hj6K
So I tried to convert it into class, but apparently it gives me an error and I cannot see how to fix it.
My teached also said that I don't have to keep it as an array, and could instead make many variables instead of the data in the array.
The language is processing and gives error code NullPointerException
class Button
{
int[] nums;
Button(int n1, int n2, int n3, int n4)
{
nums[0] = n1;
nums[1] = n2;
nums[2] = n3;
nums[3] = n4;
}
void display()
{
fill(255, 0, 0);
rect(nums[0], nums[1], nums[2], nums[3]);
}
};
void setup()
{
size(800, 800);
Button butt = new Button(75, 250, 200, 200);
butt.display();
}
You're only declared nums, but not initialized it.
This results in a NullPointerException: in the constructor you're accessing nums[0], but nums doesn't have a length yet. Try this:
class Button
{
//remember to initialize/allocate the array
int[] nums = new int[4];
Button(int n1, int n2, int n3, int n4)
{
nums[0] = n1;
nums[1] = n2;
nums[2] = n3;
nums[3] = n4;
}
void display()
{
fill(255, 0, 0);
rect(nums[0], nums[1], nums[2], nums[3]);
}
};
void setup()
{
size(800, 800);
Button butt = new Button(75, 250, 200, 200);
butt.display();
}
In the future, always make sure the variables you try to access properties of(arrays/objects) are initialized/allocated first(otherwise you'll get the NullPointerException again and it's no fun)
As #v.k. so nicely points out, it's better to have readable code and remove some of the redundancy.
Before the x,y,width and height of your button were stored in an array. That is all the array could do: store data and that's it! Your class however can not only store the same data as individual easy to read properties, but can also do more: functions! (e.g. display())
So, the more readable version:
class Button
{
//remember to initialize/allocate the array
int x,y,width,height;
Button(int x,int y,int width,int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
void display()
{
fill(255, 0, 0);
rect(x,y,width,height);//why don't we use this.here or everywhere ?
}
};
void setup()
{
size(800, 800);
Button butt = new Button(75, 250, 200, 200);
butt.display();
}
Yeah, it's sorta easier to read, but what's the deal with this you may ask ?
Well, it's a keyword that allows you to gain access to the object's instance (which ever that may be in the future when you choose to instantiate) and therefore it's properties (classes version of variables) and methods (classes version of functions). There's quite a lot of neat things to learn in terms of OOP in Java, but you can take one step at a time with a nice and visual approach in Processing.
If you haven't already, check out Daniel Shiffman's Objects tutorial
Best of luck learning OOP in Processing!
Can anyone help me get this to run? I'm aiming for a custom Actor. (I have only just started hacking with Vala in the last few days and Clutter is a mystery too.)
The drawme method is being run (when invalidate is called) but there doesn't seem to be any drawing happening (via the Cairo context).
ETA: I added one line in the constructor to show the fix - this.set_size.
/*
Working from the sample code at:
https://developer.gnome.org/clutter/stable/ClutterCanvas.html
*/
public class AnActor : Clutter.Actor {
public Clutter.Canvas canvas;
public AnActor() {
canvas = new Clutter.Canvas();
canvas.set_size(300,300);
this.set_content( canvas );
this.set_size(300,300);
//Connect to the draw signal.
canvas.draw.connect(drawme);
}
private bool drawme( Cairo.Context ctx, int w, int h) {
stdout.printf("Just to test this ran at all: %d\n", w);
ctx.scale(w,h);
ctx.set_source_rgb(0,0,0);
//Rect doesn't draw.
//ctx.rectangle(0,0,200,200);
//ctx.fill();
//paint doesn't draw.
ctx.paint();
return true;
}
}
int main(string [] args) {
// Start clutter.
var result = Clutter.init(ref args);
if (result != Clutter.InitError.SUCCESS) {
stderr.printf("Error: %s\n", result.to_string());
return 1;
}
var stage = Clutter.Stage.get_default();
stage.destroy.connect(Clutter.main_quit);
//Make my custom Actor:
var a = new AnActor();
//This is dodgy:
stage.add_child(a);
//This works:
var r1 = new Clutter.Rectangle();
r1.width = 50;
r1.height = 50;
r1.color = Clutter.Color.from_string("rgb(255, 0, 0)");
stage.add_child(r1);
a.canvas.invalidate();
stage.show_all();
Clutter.main();
return 0;
}
you need to assign a size to the Actor as well, not just the Canvas.
the size of the Canvas is independent of the size of the Actor to which the Canvas is assigned to, as you can assign the same Canvas instance to multiple actors.
if you call:
a.set_size(300, 300)
you will see the actor and the results of the drawing.
Clutter also ships with various examples, for instance how to make a rectangle with rounded corners using Cairo: https://git.gnome.org/browse/clutter/tree/examples/rounded-rectangle.c - or how to make a simple clock: https://git.gnome.org/browse/clutter/tree/examples/canvas.c
I am writing a tile based platform game. At the moment I am trying to get 400 tiles to display at once. This is my panel. On the top and left sides everything is working great but on the right and bottom sides the images are cut off by a few pixels. Each image is 32*32. All of blocks are initialized. None are null. What is wrong here?
public class Pane extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
Timer timer;
boolean setup = false;
Block[][] blocks;
Level level;
public Pane()
{
level = new Level();
level.Generate();
blocks = level.Parse();
setBackground(Color.WHITE);
timer = new Timer(25, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
for(Block[] b : blocks)
{
for(Block bx : b)
{
// Debug code if(bx.letter.equals("D"))
// Debug codeSystem.out.println(bx.y*32 +" = "+ bx.x*32);
g2d.drawImage(bx.bpic, bx.x*32, bx.y*32, this);
}
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
on the right and bottom sides the images are cut off by a few pixels
If you mean the right and bottom sides of the whole panel (not on the single tiles), than it's probably a LayoutManager related problem. The solution depends on the layout manager you are using for the component your JPanel will be added to.
You could try to specify the minimum/preferred size of your JPanel with:
Pane pane = new Pane();
pane.setPreferredSize(...);
pane.setMinimumSize(...);
In order to specify its minimum dimension accordingly to the size of the generated image (32 * COL , 32 * ROW).
Unfortunately the effectiveness of the setPreferredSize call depends on the layout manager of your Pane parent component.
JComponent can do that basically and can return very easily something as MinimumSize or PreferredSize, valid for majority of standard Swing LayoutManagers, examples here.