Coder Social home page Coder Social logo

pdfbox-layout's People

Contributors

ralfstuckert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pdfbox-layout's Issues

Running on Android

Hi there. Are there some possibility to run library under Android? I'm trying to run it but only get
ClassNotFoundException: Didn't find class "java.awt.geom.AffineTransform"
Seems like library is depend on awt,

Draw on existing PDDocument?

Hi,
I'm trying to create a document that have a table in it:
/-----------------------
| text text text |

text text text
------------------
text text text
-----------------------/

I'm using pdfbox-layout for the first text paragraph than https://github.com/dhorions/boxable for the table, when I want to use pdfbox-layout again I'm encountering an issue. I cannot use pdfbox on an existing pddocument, there is no api for setting one, just creating one.
so if I do doc.getPDDocument() I receive a document without pages, adding a page manually and drawing the table and continuing adding paragraphs before the actual render gives me a table on the first page and all the text in the next pages. if I do doc.render() I can put the table on the same page as the first text but I can't draw after the table since rendering twice removes the table I drew on the previously rendered document...

My workaround was to render the text, then the table, then the text after the table end position, then render the table again on the PDDocument...

line height

Is it possible to set line height for wrapping? or just +x to every line?

please deploy to maven central

I don't like to use artifacts from repositories owned by private companies. Those can vanish every day. Also, I heard rumors that deployment to central is really easy from your current public maven host.

Enumerator Numbering Doesn't Increment

I'm using the markup for a numbered list, but I noticed that the numbering doesn't seem to increment at all for me. I am using '-#' as the markup for a list and '-!' to end the list, but it seems to do 1 as the bullet point for every entry.

I tried using {I:5} to specify Roman to see if that changes anything, but it just labels every item with I.

I'm wondering if there is something wrong or if there is something I need to do in addition to creating the TextFlow, setting up the annotationDrawListener, and calling the beforePage, drawText, afterPage, and afterRender methods?

Thanks!

Wrap text when longer then width of the page

Like in CSS when have text like:
foo-bar-fooooooooo-bbbaaaaaaaarrrrrr

and page width is
--------------------------

It will break text in - points to get:

foo-bar-fooooooooo-
bbbaaaaaaaarrrrrr

Are we able to do the same thing here?

Text wrapping runs forever when the constraints are impossible to fullfill.

I found an issue in the word breaker logic in the project.

Given a word that will never fit in the given constraints, the word breaker runs forever.

It sprung out when using the Paragraph class, but I figured dove into it and found the bug in the WordBreakers class logic.

The tests below show the error at hand.

@Test(timeout = 5_000L)
public void wordBreakerTerminatesWhenAttemptingImpossibleWrap() throws Exception {
    Paragraph paragraph = new Paragraph();
    paragraph.add(new StyledText("N", 12, PDType1Font.COURIER));

    List<TextLine> lines = TextSequenceUtil.wordWrapToLines(paragraph, 2);
    Assert.assertEquals(1, lines.size());

    TextLine line = lines.get(0);
    Assert.assertEquals("N", line.getStyledTexts().get(0).getText());
}

The above runs forever because the wrap function returns a pair Pair("", "N").
I wrote another test verifying this closer to the word breaking logic:

@Test
public void wordBreakerHasEmptyStringAsTheSecondPairWhenAttemptingImpossibleWrap() throws Exception {
    FontDescriptor fontDescriptor = new FontDescriptor(PDType1Font.COURIER, 5);

    WordBreaker workBreaker = WordBreakerFactory.getWorkBreaker();
    Pair<String> broken = workBreaker.breakWord("H", fontDescriptor, 1, true);

    Assert.assertEquals("The first entry should be 'H'", "H", broken.getFirst());
    Assert.assertEquals("The second entry should be the empty string", "", broken.getSecond());
}

TextFlow: capping the height

Would it be possible to create a text flow, capping its height, and then ask it to render and return, in a way or another, the characters which couldn't be rendered within the selected height?
(context: I have a project which I need to migrate away from PdfClown, and its BlockComposer provided such an api: showText(String text) returns Last shown character index. This was pretty useful for pagination/page breaks inside tables).

Aligment justified

Is there any way to set paragraph aligment justified? I only see these choices: center, left, right.

Not optimal ImageElement

A few points about images

  1. ImageElement based on BufferedImage that stores decoded (uncompressed) image bitmap. It could occupy more then 50MB per image. And doesn't matter if it is JPEG or PNG.
  2. To create PDImageXObject is used LosslessFactory. In this case compression not optimal at least for JPEG types.

Proposal:

  1. Update ImageElement to use image source inputs stream or byte array (compressed).
  2. To detect width and height just use ImageIO.getImageReaders(is)``, ``reader.getWidth(0), reader.getHeight(0)
  3. Then on draw call PDImageXObject.createFromByteArray() - new method in PDFBox 2.0.8

Note:
createFromByteArray() - it also not optimal due to reading all stream (one time) instead of parse only header to detect color space. Anyway stream / byte array is compressed it is better than BufferedImage

Indentation for a table

Hi Ralf,
Would you please provide apis for writing large data dynamically in the form of a table in pdfbox.
Example 1: Please find attachment for the sample format.
Example 2: If the content in row number 1 is exceeding the limit, it should automatically go to the new line. It shouldnot disturb the indentation. Please find 2nd attachment
Hello World 2.docx

Hello World.docx

Problems loading font file in Spring Boot

I am using this method to load fonts that are in my resource folder:

PDType0Font obscuraFont = PDType0Font.load( document.getPDDocument(), new File(file.ttf"));

Works fine before creating the jar file, But once created the file jar no longer finds the resources this is because spring boot does not allow to search within the jar class path, For this you have to use a InputStream but I could not make it work.

I'm looking for an implementation of PDType0Font.load that will serve with Streams or another way to load Fonts that is compatible with spring boot in production

Underline Not Printing

I'm using the underline annotation and it looks great when viewing the PDF document in Adobe Reader. The problem I'm having is that when I print the PDF document the underlines are not printed. Is there something special I need to do to make the underlines print?

Dynamic Content In A Page Header/Footer

Is there a way to have dynamic content in a page header/footer? I setup a RenderListener that I'm using to print a header and footer on my report. It works great except for one place in the header where I need some dynamic content. I tried creating a new RenderListener and adding it to the document when I do a document.add(ControlElement.NEWPAGE) but that didn't work.

Any thoughts?

Thanks.

Escape markup / control characters

It would be nice to have a helper function for escaping markup characters in string.

For example if text is dynamically created or stored in DB and contains special symbols (_, *. \n..) which shouldn't be rendered but at the same time could have color.

The workaround is to create manually each element: new StyledText(), new NewLine()...

Provide an option to avoid the removal of leading white spaces when drawing/layouting an element

When outputting code (java, or formatted markup like yaml), it would be nice to have a simple way to keep the leading white spaces.

I tried something similar to your algorithm

        TextFlow flow = new TextFlow();

        int textStart = 0;
        Matcher matcher = PATTERN_LEADING_SPACES.matcher(text);
        while (matcher.find()) {
            if (0 <= textStart) {
                flow.addText(text.substring(textStart, matcher.start()), FONT_SIZE_TABLE, PDType1Font.COURIER);
                textStart = matcher.end();
            }
            String group = matcher.group();
            int indent = 0;
            for (char character : group.toCharArray()) {
                if ('\t' == character) {
                    indent += 4;
                } else {
                    indent += 1;
                }
            }
            flow.addMarkup(String.format("--{%sem}", indent), FONT_SIZE_TABLE, BaseFont.Courier);
        }
        flow.addText(text.substring(textStart), FONT_SIZE_TABLE, getFixedWidth());
        return flow;

and this works, in a way (but is quite cumbersome) and ends up showing something slightly weird for my samples (some lines are "spaced" when they shouldn't):
image

It looks like newlines are inserted, but there are no newlines.
I might be wrong, but this appears to be because TextSequenceUtil.wordWrap creates new instances of "Indent",
new Indent(indentation).toStyledText() which are using default font and size.
When remote debugging, the indentation seems to use FontDescriptor [font=PDType1Font Helvetica, size=11.0] instead of FontDescriptor [font=PDType1Font Courier, size=7.0] from the text.

Default orientation in PageFormat overrides mediabox intended orientation

If you create a PageFormat with a media box with landscape format (width > height), than it will be rotated by 90 degrees to portrait, since this is the default orientation. See the following example where the A4 width and height are swapped:

PageFormat landscape = PageFormat.with().mediaBox( new PDRectangle( Constants.A4.getHeight(), Constants.A4.getWidth())) .build();

The resulting PDF is not landscape but portrait.

Fit text into space

I have to fit text into precise width, height.

For example i have to write on PDF "foo bar baz foo bar baz foo bar baz foo bar baz ..." in XxY. If it doesn't fit i have to decrease font-size as long as it will start fit. How can i do it? How to check how much space parahraph will consume on the page?

Wrong text possition in frame

Hi,

Description:
The following issue is appeared in Frame with Paragraph if setMaxWidth > 0.
Depends on alignment:

  • left: all ok
  • center: text moved to the right a bit
  • right: text moved again to the right and overlaps frame border

Investigation:
The frame border width is based on inner.getWidth() (see: TextSequenceUtil.getWidth()) which can be less then maxWidth.
At the same time in TextSequenceUtil.drawText() the maxLineWidth variable is a max of getMaxWidth(lines) and maxWidth. It means that variable in common case is equal to maxWidth.
As result frame width < maxLineWidth (used for text positioning)

Workaround - set paragraph maxWidth the same as width :
paragraph.setMaxWidth(width); paragraph.setMaxWidth(paragraph.getWidth());

Possible fixes (frame border should be equal to max line width) :

  • draw frame border based on inner.getMaxWidth() instead of inner.getWidth()
  • fix TextSequenceUtil.drawText() and use min() function to calculate maxLineWidth

jump to position Y

I am writing text in PDF and no matter what is the height i have to jump to specific Y position and continue.

So:

foo
bar
#jump to Y position and continue, just want start this part of the PDF always from that place whatever i wrote before
baz

How can i do that?

MemoryUsageSetting

By default document is created in memory but if you have big PDF with lot of images you might catch OutOfMemoryError.
Could you please add a possibility to setup MemoryUsageSetting for PDDocument ?

Maven central

Could you deploy your artifact to Maven central please.
It would be much more easier to use it, because u don't need to add additional repositories to your project.
Thank you.

New page rotation issue

Look like a bug in condition: isPageTilted() - it always returns false.

RenderContext.java

public void newPage() throws IOException {
        ...
        this.page = new PDPage(getPageFormat().getMediaBox());
        ....
	// fix orientation
	if (getPageOrientation() != getPageFormat().getOrientation()) {
	    if (isPageTilted()) {                   // <---- HERE IS BUG!
		page.setRotation(0);
	    } else {
		page.setRotation(90);
	    }
	}

Possible fix:

if (getPageFormat().getOrientation() == Orientation.Landscape) {
    page.setRotation(90);
}

Support of additional level 'Flow'

I saw that pdfbox-layout has frames in a document and paragraphs in a frame. I need one more level between document and frame that can be places to specific positions.

  • Document has flows
  • Flow has frames
  • Frame has paragraphs

Flows have for example Parameters like: xCoord, yCoord, width and height.

How can I do this? Is there already existing something similar?

rotate page by 90 degree

I found something like that:

PageFormat a5_landscape = 
PageFormat.with().mediaBox(
new PDRectangle( Constants.A5.getHeight(),Constants.A5.getWidth()))
.orientation(Orientation.Landscape)
.margins(hMargin, hMargin, 100f, 130f)
.build();

but it only change dimension form XxY to YxX. It is worthless. It doesn't rotate the content.

Also i found:

document.getPDDocument().getPage(0).setRotation(90);

But is it really no way to set rotation directly on the page?

Underline and Strikethrough Markup on Same Text

I was wondering how would I go about adding underline and strikethrough to the same content by using the markup? Since the markup for underline and strikethrough is the same it seems like it parses the first "__" but then doesn't see the second one.

The same issue happens with italic and either one of those too because italic uses "_" and these use "__" for the markup.

I was thinking changing the annotation for some of these would fix this, but I'm not entirely sure how to do that.

Thanks!

Is it possible to have an image directly followed by text (on the same line) ?

Hi,

I've tried to have an image directly followed by some text, but I did not manage to achieve it.
I've tried using the ColumnLayout but if the text and the image are indeed on the same line, there is a lot of space between them. As the number of line and image can vary, I won't have the current possition available.

Is that possible using pdfbox-layout ?

Thanks in advance.

David

Switching between columns and vertical layout

Is it possible to switch between column layout then back to vertical layout then back to column layout etc ad nauseam ?
I'm not expecting that it is, but just wanted to check I'm not missing something ?
Thanks,
chris

Make paragraph fill the entire page

Hi, first of all thank you for this library!

Is there any way to have one paragraph per page?
I have a list of strings and I want to create a PDF document with each string on its on page.

Proposals

  1. Alignment enums and helpers for element positioning at TOP, CENTER and BOTTOM
  2. New element type - AnnotationElement (with new Renderer) to have a possibility for adding any kind of
  • available annotations on page: SquareCircle, Line, RubberStamp, File, Stream etc (see: PDAnnotationXXX)
  • or any new (not defined yet in PDFBox): Video, Audio, etc
  1. Some wrapper to link Drawable element with annotation. I sow Annotated interface but in this case if I want to have clickable image I need to implement new AnnotatedImageElement class, override getAnnotationsOfType() , iterator() and create own AnnotationProcessor.

Vertical position after ColumnLayout is based on the last column rather than the longest

Example:

document = new Document(40, 50, 40, 60);
document.add(new ColumnLayout(2, 0));
for (int i=0; i < 20; ++i) {
  Paragraph p = new Paragraph();
  p.addText("Column 0 Line " + i, 10, PDType1Font.HELVETICA);
  document.add(p);
}
document.add(ColumnLayout.NEWCOLUMN);
for (int i=0; i < 10; ++i) {
  Paragraph p = new Paragraph();
  p.addText("Column 1 Line " + i, 10, PDType1Font.HELVETICA);
  document.add(p);
}
document.add(new VerticalLayout(), VerticalLayoutHint.LEFT);
Paragraph p = new Paragraph();
p.addText("This should be below the first column", 10, PDType1Font.HELVETICA);
document.add(p);

image

If that is intentional, is there a way to reset the position to below the first column? Or is there a workaround other than filling the second column with blank paragraphs?

Thanks!

Combing elements into a paragraph

Hi,
Just looking to see if this library will help me at all - certainly has potential, however I am struggling to work out how I might do my most important need. That is to have a number of paragraphs which are in turn a combination of paragraphs themselves.
For instance I would like a paragraph with a centred heading, followed by two columns of text and all within a border. This box of paragraphs might then be only half a page wide with a similar box of paragraphs next to it.
Ideally, if a paragraph could be built up from other paragraphs and then included in a frame, that would work nicely but I don't seem to be able to get that working.
Any ideas or pointers in the right direction ?
Thanks,
chris

File Compression

Is there a way to compress the resulting PDF file prior to writing it to a ServletOutputStream? I've noticed the resulting files are much larger than expected.

Underline Text

Hello,

I just started using the latest version of pdfbox-layout and really like the functionality it provides. It has made my PDF generation efforts much easier. I have a question, tho. How do I underline text?

For example:
Paragraph paragraph = new Paragraph();
paragraph.addText("NAME", 12, BaseFont.Times.getPlainFont()); // NAME needs to be underlined
document.add(paragraph, VerticalLayoutHint.RIGHT);

Thanks for any insight.

Absolute positioning

I like pdfbox-layout very much. But it seems that it does not fit my purpose. Or I failed to learn it well. I want to place various sections across the page at precise location and add there either paragraph or image. For example one picture on left, another on right and text below the picture aligned to it, both 5 cm from top. Then there will be a paragraph starting 10cm from top of the page. Etc. Is this possible?

Stop ColumnLayout

Hi is there a Way to stop the ColumnLayout and continue with a VerticalLayout?

doc.add(new VerticalLayout()); didn't work

Add filled rectangle - miss the example of code in wiki

When using PDDocument directly i can use PDPageContentStream with doc and page parameter to draw a rectangle.

(let [doc (PDDocument.)
        page (PDPage. (PDRectangle. (mm->points 43) (mm->points 58)))
        content (PDPageContentStream. doc page)]
(doto content
      (.addRect 0 0 (mm->points 43) (mm->points 6))
      (.setNonStrokingColor Color/RED)
      (.fill)))

How can i draw a rectangle when using pdfbox-layout?

I thought it works like paragraph:

(let [rect (Rectangle. 0 0 (Rectangle. 0 0 (mm->points 43) (mm->points 6)))]
(doto doc
      (.add rect)
      (.add parahraph VerticalLayoutHint/CENTER)
      (.save (clojure.java.io/file path))))

But it throws an exception:
CompilerException java.lang.ClassCastException: rst.pdfbox.layout.elements.Rectangle cannot be cast to rst.pdfbox.layout.elements.Element

What i miss?

Indentation damaged?

As soon as I use the following method, the corresponding paragraph seems to be damaged and is empty:

Paragraph paragraph = new Paragraph();
paragraph.add(new Indent(50, SpaceUnit.pt));
paragraph.addMarkup(content, fontSize, resolvedBaseFont);

Is there maybe something damaged?

Thank you.

Improve the word-wrapping/word-breaking support

As of now, word-wrapping happens at word boundaries. (through TextSequenceUtil.drawText -> wordWrapToLines -> wordWrapToLines)
This can be annoying for small columns where a single big word needs to be inserted or if Justify is supported as alignment someday.

It would be nice to be able to

  • force a line break inside the word if there is not enough place to put the word on the line (and there is no "white space" available for pdfbox-layout to break automatically) ("hard cut")
  • provide a "strategy" when drawing a TextFlow that would hint to pdfbox-layout where clean "soft cuts" can be inserted into a word (see https://en.wikipedia.org/wiki/Hyphenation_algorithm)
  • make pdfbox-layout write an hyphen when a soft/hard cut happened (maybe a configurable character for hard cut)

Custom Fonts in Document API

I was wondering if it was possible to both use the Document API and load custom Fonts (such as Arial) to use. I know that it's possible with pdfbox so I could use the Text API and load the fonts that way, but I believe certain markup doesn't seem to work in only the Text API: underline, strike through, lists, and etc.

Please let me know if I totally missed something and there is a way to load custom fonts or if I'm not using the markup correctly in the Text API.

a

a

Get Position Of Text

Hello,

Is it possible to get the position of text after it has been added to a paragraph? Using the following, I'd like to be able to find the position (x,y) of where NAME has been added the paragraph.

Paragraph paragraph = new Paragraph();
paragraph.addText("NAME", 12, BaseFont.Times.getPlainFont());
document.add(paragraph, VerticalLayoutHint.RIGHT);

Thanks you.

Change paragraph text color

Is it possible to change a paragraph text color?
having multiple paragraphs with different colors on the same page?

something like this?
paragraph.addText"example", 11, arial, Color.green)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.