Removing newlines when continuing a column on a new page - itext

I am using iTextSharp to generate a PDF on the fly. I am using the ColumnText class in text mode using the ColumnText.SetColumns() method to define column boundaries using code like the following:
myColumnText.SetColumns(leftCoords, rightCoords)
myColumnText.AddText(New Chunk("Lorem ipsum..."))
myColumnText.AddText(Chunk.NEWLINE))
myColumnText.AddText(Chunk.NEWLINE))
myColumnText.AddText(New Chunk("Lorem ipsum..."))
myColumnText.AddText(Chunk.NEWLINE))
myColumnText.AddText(Chunk.NEWLINE))
As you can see, I emit a block of text and then two Chunk.NEWLINEs to add whitespace between paragraphs.
I then use ColumnText.Go to emit the content, creating new pages as needed, like so:
While ColumnText.HasMoreText(myColumnText.Go())
myDocument.NewPage()
myColumnText.SetColumns(leftCoords, rightCoords)
End While
The problem I am running into is that depending on the content in the ColumnText object a page break might occur right at the end of a chunk of text but before the Chunk.NEWLINEs, meaning that the content on the next page starts with two Chunk.NEWLINEs rather than at the top of the page.
Is there a way to somehow suppress Chunk.NEWLINEs if they are the first things emitted on a new page? My thought was that if I could somehow see the text that was about to be emitted by ColumnText.Go I could see if I was about to emit a Chunk.NEWLINE and remove it from the content stream or something...
Thanks

Related

iTextSharp extracts wrapped cell contents into new lines - how do you identify to which column a given wrapped piece of data belongs now?

I am using iTextSharp to extract data from pdfs.
I stumbled across the following problem, depicted by the scenario below:
I created a sample excel file to illustrate. Here is what it looks like:
I convert it to a pdf, using one of the many free online converters available out there, which generates a pdf looking like (when I generated the pdf I did not apply the styling to the excel):
Now, using iTextSharp to extract the data from the pdf, returns me the following string as the data extracted:
As you can see, wrapped cell data generate new lines, where each wrapped piece of data separated by a single white space.
The problem: how does one identify, now, to which column a given piece of wrapped data belongs to ? If only iTextSharp preserved as many white spaces as columns...
In my example - how can I identify to which column does 111 belong ?
Update 1:
A similar problem occurs whenever a field has more than one word (i.e., contains white spaces). For example, considering the 1st line of the sample above:
say it looked like
---A--- ---B--- ---C--- ---D---
aaaaaaa bb b cccc
iText again would generate the extraction for this one as:
aaaaaaa bb b cccc
Same problem here, in having to determine the borders of each column.
Update 2:
A sample of the real pdf file I am working with:
This is how the pdf data looks like.
In addition to Chris' generic answer, some background in iText(Sharp) content parsing...
iText(Sharp) provides a framework for content extraction in the namespace iTextSharp.text.pdf.parser / package com.itextpdf.text.pdf.parser. This franework reads the page content, keeps track of the current graphics state, and forwards information on pieces of content to the IExtRenderListener or IRenderListener / ExtRenderListener or RenderListener the user (i.e. you) provides. In particular it does not interpret structure into this information.
This render listener may be a text extraction strategy (ITextExtractionStrategy / TextExtractionStrategy), i.e. a special render listener which is predominantly designed to extract a pure text stream without formatting or layout information. And for this special case iText(Sharp) additionally provides two sample implementations, the SimpleTextExtractionStrategy and the LocationTextExtractionStrategy.
For your task you need a more sophisticated render listener which either
exports the text with coordinates (Chris in one of his answers has provided an extended LocationTextExtractionStrategy which can additionally provide positions and bounding boxes of text chunks) allowing you in additional code to analyse tabular structures; or
does the analysis of tabular data itself.
I do not have an example for the latter variant because generically recognizing and parsing tables is a whole project in itself. You might want to look into the Tabula project for inspiration; this project is surprisingly good at the task of table extraction.
PS: If you feel more at home with trying to extract structured content from a pure string representation of the content which nonetheless tries to reflect the original layout, you might try something like what is proposed in this answer, a variant of the LocationTextExtractionStrategy working similar to the pdftotext -layout tool; only the changes to be applied to the LocationTextExtractionStrategy are shown there.
PPS: Extraction of data from very specific PDF tables may be much easier; for example have a look at this answer which demonstrates that after some PDF analysis the specific way a given table is created might give rise to a simple custom render listener for extracting the table data. This can make sense for a single PDF with a table spanning many many pages like in the case of that answer, or it can make sense if you have many PDFs identically created by the same software.
This is why I asked for a representative sample file in a comment to your question
Concerning your comments
Still with the pdf example above, both with an implementation from scratch of ITextExtractionStrategy and with extending LocationExtractionStrategy, I see that each RenderText is called at the following chunks: Fi, el, d, A, Fi, el, d... and so on. Can this be changed?
The chunks of text you get as separate RenderText calls are not separated by accident or some random decision of iText. They are the very strings drawn separately in the page content!
In your sample "Fi", "el", "d", and "A" come in different RenderText calls because the content stream contains operations in which first "Fi" is drawn, then "el", then "d", then "A".
This may sound weird at first. A common cause for such torn up words is that PDF does not use the kerning information from fonts; to apply kerning, therefore, the PDF generating software has to insert tiny forward or backward jumps between characters which should be farther from or nearer to each other than without kerning. Thus, words often are torn apart between kerning pairs.
So this cannot be changed, you will get those pieces, and it is the job of the text extraction strategy to put them together.
By the way, there are worse PDFs, some PDF generators position each and every glyph separately, foremost such generators which predominantly build GUIs but can as a feature automatically export GUI canvasses as PDFs.
I would expect that in entering the realm of "adding my own implementation" I would have control over how to determine what is a "chunk" of text.
You can... well, you have to decide which of the incoming pieces belong together and which don't. E.g. do glyphs with the same y coordinate form a single line? Or do they form separate lines in different columns which just happen to be located next to each other.
So yes, you decide which glyphs you interpret as a single word or as content of a single table cell, but your input consists of the groups of glyphs used in the actual PDF content stream.
Not only that, in none of the interface's methods I can "spot" how/where it deals with non-text data/images - so I could intercede with the spacing issue (RenderImage is not called)
RenderImage will be called for embedded bitmap images, JPEGs etc. If you want to be informed about vector graphics, your strategy will also have to implement IExtRenderListener which provides methods ModifyPath, RenderPath and ClipPath.
This isn't really an answer but I needed a spot to show some things that might help you understand things.
First "conversion" from Excel, Word, PowerPoint, HTML or whatever to PDF is almost always going to be a destructive change. The destructive part is very important and it happens because you are taking data from a program that has very specific knowledge of what that data represents (Excel) and you are turning it into drawing commands in a very generic universal format (PDF) that only cares about what the data looks like, not the data itself. Unless the data is "tagged" (and it almost never is these days still) then there is no context for the drawing commands. There are no paragraphs, there are no sentences, there are no columns, rows, tables, etc. There's literally just draw this letter at x,y and draw this word at a,b.
Second, imagine you Excel file had that following data and for some reason that last column was narrower than the others when the PDF was made:
Column A | Column B | Column
C
Data #1 Data #2 Data
#3
You and I have context so we know that the second and fourth lines are really just the continuation of the first and third lines. But since iText doesn't have any context during extraction it doesn't think like that and it sees four lines of text. In fact, since it doesn't have context it doesn't even see columns, just the lines themselves.
Third, although a very small thing you need to understand that you don't draw spaces in PDF. Imagine the three column table below:
Column A | Column B | Column C
Yes
If you extracted that from a PDF you'd get this data:
Column A | Column B | Column C
Yes
Inside the PDF the word "Yes" will be just drawn at a certain x coordinate that you and I consider to be under the third column and it won't have a bunch of spaces in front of it.
As I said at the beginning, this isn't much of an answer but hopefully it will explain to you the problem that you are trying to solve. If your PDF is tagged then it will have context and you can use that context during extraction. Context isn't universal, however, so there usually isn't just a magic "insert context" checkbox. Excel actually does have a checkbox (if I remember correctly) to make a tagged PDF during export and it ultimately creates a tagged PDF using HTML-like tags for tables. Very primitive but it will works. However it will be up to you to parse this context.
Leaving here an alternative strategy for extracting the data - that does not solve the problem of who are spaces treated/can be treated, but gives you somewhat more control over the extraction by specifying geometric areas you want to extract text from. Taken from here.
public static System.util.RectangleJ GetRectangle(float distanceInPixelsFromLeft, float distanceInPixelsFromBottom, float width, float height)
{
return new System.util.RectangleJ(
distanceInPixelsFromLeft,
distanceInPixelsFromBottom,
width,
height);
}
public static void Strategy2()
{
// In this example, I'll declare a pageNumber integer variable to
// only capture text from the page I'm interested in
int pageNumber = 1;
var text = new StringBuilder();
List<Tuple<string, int>> result = new List<Tuple<string, int>>();
// The PdfReader object implements IDisposable.Dispose, so you can
// wrap it in the using keyword to automatically dispose of it
using (var pdfReader = new PdfReader("D:/Example.pdf"))
{
float distanceInPixelsFromLeft = 20;
//float distanceInPixelsFromBottom = 730;
float width = 300;
float height = 10;
for (int i = 800; i >= 0; i -= 10)
{
var rect = GetRectangle(distanceInPixelsFromLeft, i, width, height);
var filters = new RenderFilter[1];
filters[0] = new RegionTextRenderFilter(rect);
ITextExtractionStrategy strategy =
new FilteredTextRenderListener(
new LocationTextExtractionStrategy(),
filters);
var currentText = PdfTextExtractor.GetTextFromPage(
pdfReader,
pageNumber,
strategy);
currentText =
Encoding.UTF8.GetString(Encoding.Convert(
Encoding.Default,
Encoding.UTF8,
Encoding.Default.GetBytes(currentText)));
//text.Append(currentText);
result.Add(new Tuple<string, int>(currentText, currentText.Length));
}
}
// You'll do something else with it, here I write it to a console window
//Console.WriteLine(text.ToString());
foreach (var line in result.Distinct().Where(r => !string.IsNullOrWhiteSpace(r.Item1)))
{
Console.WriteLine("Text: [{0}], Length: {1}", line.Item1, line.Item2);
}
//Console.WriteLine("", string.Join("\r\n", result.Distinct().Where(r => !string.IsNullOrWhiteSpace(r.Item1))));
Outputs:
PS.: We are still left with the problem of how to deal with spaces/non text data.

How to create a block letters form input in libreoffice writer

I would like to create a document including a input form.
The printed version of the form should have little boxes for block letter input ("monospace font") like this:
The form will be printed and will be filled out manually using pens (but it would be good if the form could also be easily filled out digitally via pdf form)
Is there any convenient way apart from creating separate input boxes, or tables or other quick fixes which do not make it inconvenient filling the form digitally?
One way could be to use a background image with the required block pattern.
If you only want it printable - create a document and set the image as background.
If you want a computer fillable form for a SEPA banking transaction form - do a search, as there are free PDF forms available.

Merging documents using OpenXml and section breaks causes empty paragraphs

I am stitching a couple of documents together with a requirement that each document should retain its header and footer information in the final document. Using AltChunk instead of raw OpenXml or DocumentBuilder saves a lot of effort with regards to styles, formatting, references, parts, etc.
Unfortunately, after a couple of days I can't seem to get a 100% working version due to a small and frustrating issue and I need some insight.
My code is loosly based on this article
I modify each sub document, prior to appending it (as an AltChunk) to a working document, by moving the last section properties into the last paragraph (in order to retain header and footer references), but Word seems to be adding a blank paragraph to each of these documents as it renders them in the final document. I end up with:
document 1 with correct header and footer
section properties/break
blank paragraph
document 2 with correct header and footer
section properties/break
blank paragraph
etc.
I cant remove the blank paragraphs afterwards, as I ideally don't want to use WAS to render the document first.
It seems as if you cannot have a next-page section break without a following paragraph?
After further investigation, it seems that will not be away around my usage scenario. I would need to place the last section properties in the body element, but due to my way of processing with nested AltChunk, it would not work.
I have changed my approach completely and went back to a more detailed append procedure using OpenXml Power Tools and some LINQ to Xml.
I'm using Document Builder and works perfectly for me!
var sources = new List<OpenXmlPowerTools.Source>();
sources.Add(new OpenXmlPowerTools.Source(new WmlDocument(#tempReportPart1)));
sources.Add(new OpenXmlPowerTools.Source(new WmlDocument(#tempReportPart2)));
var outputPath = #"C:\Users\xpto\Documents\TestFolder\myNewDocument.docx";
DocumentBuilder.BuildDocument(sources, outputPath);
I have the similar empty paragraph issue while importing HTML files.
My solution is,
After inserting HTML AltChunk, I add a GUID place holder. After processing the file, I will open the file again, locate the GUID and check if there is a empty paragraph before it, if so remove the empty paragraph and GUID. it seems work perfectly in my solution.
Hope it helps.

CKEditor insert empty paragraph

In the CKEditor plugin I'm writing, i need to create a new empty paragraph.
I know that empty paragraphs (<p></p>) are collapsed by most browsers, that is why CKEditor has some special handling for them:
When displaying the HTML source, CKEditor displays <p> </p> for an empty paragraph (for example, when you press enter twice)
Depending on the browser, in the editing area CKEditor fills the Paragraph with another placeholder. For example in Mozilla Firefox, it inserts a <br type="_moz" /> into the paragraph.
However, when inserting a p DOM node manually (using the CKEditor dom object), this special handling is omitted. It magically appears when i switch to source view and back edit mode, though.
I've tried:
var new_p = new CKEDITOR.dom.element('p');
editor.insertElement(new_p);
And:
var new_p = new CKEDITOR.dom.element.createFromHtml('<p></p>');
editor.insertElement(new_p);
And also:
editor.insertHtml('<p>');
But the special handling of the empty paragraph does not take place. I get an empty Paragraph, but as the Browser is collapsing it, I can't see or edit its content correctly.
When switching back and forth to the source code view, CKEditor detects the empty paragraph and inserts the filler. Also when submitting the data. But i need the filler to appear immediately when inserting the new node.
How do i get CKEditor to handle my new paragraph like any other empty paragraph it would create when a user hits Enter twice?
I know i could also insert manually as HTML content to the new DOM node, but thats a huge difference - because in this case, the space really appears in the editing area, so when a user enters content into the new paragraph, he must delete the non-breaking space manually.
After researching how CKEditor handles the press of [ENTER] internally, i came to this solution:
var new_node = new CKEDITOR.dom.element( 'p' );
// insert UTF-16 non-breaking space
var dummy = editor.document.createText( '\u00A0' );
dummy.appendTo( new_node );
editor.insertElement(new_node);
// move cursor to beginning of new element
var range = editor.createRange();
range.moveToPosition( new_node, CKEDITOR.POSITION_AFTER_START );
editor.getSelection().selectRanges( [ range ] );

How to add a simple text label in a jqGrid form?

When using the Add or Edit form from the pager I'm wondering how a simple static label can be added in the form without it creating any additional columns in it's affect on colNames[]'s and colModel[]'s. For example I have a quite simple typical Add form which opens from the pager containing a few label's and form elements: Name, Email, Web Site, etc., and then the lower section of the form has a few drop down menus containing the number 1 through 10 with the idea being to ask the user to pick a value between 1 and 10 to put a value on the importance to them about the product or service which is listed beside it. Just above this section I want to add some text only to give a brief instruction asking the user to "Choose the importance of the following products and services using the scale: [1=Low interest --- 10=Very high interest]". I cannot figure out how to get a text label inserted in the form without having to define a column with a formoption{} etc which is not needed for just some descriptive text. I know about the "bottominfo: 'some text'" for adding text to the bottom of the form but I need to insert some text similar to that mid-way (or other positions) in the form without it affecting the tabular structure of the grid. Is this even possible? TIA.
You can modify Edit or Add forms inside of afterShowForm. The ids of the form fields are like "tr_Name". There consist from "tr_" prefix and the corresponding column name.
I modified the code example from my old answer so that in the Add dialod there exist an additional line with the bold text "Additional Information:". In the "Edit" dialog (like one want in the original question) the input field for one column is disabled. You can see the example live here. I hope that a working code example can say more as a lot of words.