JEditorPane (JTextComponent) print HTML and fit to page - java

I have a problem with printing out HTML content. In details HTML is not scaled to fit the page and most of long line is cut off and rest of the line is wraped. I want to use print implementation from JTextComponent because I can pass footer element with page numbering.
Here is full code:
String line = "That's really long text line because it's containing one hundred character, so believe me it is long";
JEditorPane p = new JEditorPane();
p.setContentType("text/html");
StringBuilder htmlContent = new StringBuilder();
htmlContent.append("<html>");
htmlContent.append("<head>");
htmlContent.append("</head>");
htmlContent.append("<body>");
htmlContent.append("<table width = \"845\">");
htmlContent.append("<tr>");
htmlContent.append("<td>");
for(int i = 0 ; i < 100 ; i ++)
htmlContent.append("<font face=\"monospace\">" + line + "</font><br>");
htmlContent.append("</td>");
htmlContent.append("</tr>");
htmlContent.append("</table>");
htmlContent.append("</body>");
htmlContent.append("</html>");
MessageFormat footer = new MessageFormat(" Page #{0,number,integer}");
MessageFormat header = new MessageFormat("");
p.setText(htmlContent.toString());
p.print(header, footer, false, null, null, false);
Is there any way to force this print implementation to scale HTML content do page width?
Screenshot from my result (bottom of page):
HTML printed with JEditorPane
I have tried also to make font smaller with adding size attribute to HTML font element.
I have also tried to Override print method, but I don't know Swing components well and I have a problem with adding constant footer "near" the JEditorPane - in this case JEditorPane just takes all the printable area.
Thank you for any help.

Related

Set position and rotation of text in pdf with itextpdf

I was trying to find out how to set the text position and rotation in a pdf with the "itextpdf" dependency. My current code looks like that:
//Create the pdf document
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
PdfContentByte pdfCB = new PdfContentByte(writer);
//Create the font which will be used
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
//Open the document
document.open();
//Get the image which was previously created (Not important for this)
Image iTextImage = Image.getInstance(pdfCB, image, 1);
//Set the position of the image (How do I do that with the text?)
iTextImage.setAbsolutePosition(0, 0);
//Create a text chunk which I want to set the position of and rotate
Chunk chunk = new Chunk("Hello World!", font);
//Add both the image and text to the pdf and save it
document.add(iTextImage);
document.add(chunk);
document.close();
//Notify the user that it was a success
System.out.println("Image added successfully and PDF file created!");
Now I was wondering how to set the position and rotation of the text. I want to create PDF's for a project which will later be printed. Now I don't want to add like a hundred whitespace's each time there is a blank spot in the page like the table of contents and then a footer at the bottom. I don't want to write the table of contents and then do \n 20 times to reach the bottom, so I can add my footer text, like page number, author, project ID, date, company logo, etc.
So how do I best position the text here? Also, I would like to rotate it, since some of the text has to be turned by 90 degrees for stuff like labels for tables and so on.
Any help would be appreciated, thank you.
PS: I already tried to set the absolute position, which just makes the text disappear.

iText7: How to add text to the bottom of last page?

I am new to iText7, and I want to add a text after the content in the last page. I basically got a pdf file and create a new one, copying the pages from the first into the last. After, I get the last page and tried to append some text:
PdfPage lastPage = pdfOut.getLastPage();
PdfCanvas canvas = new PdfCanvas(lastPage.newContentStreamAfter(), lastPage.getResources(), pdfOut);
Paragraph paragraph = new Paragraph().add(new Text("Este documento foi assinado Hoje"));
Canvas c = new Canvas(canvas, pdfOut, rect);
c.add(paragraph);
c.close();
The text is not being appended after the content, sometimes appears in the first line of the last page or even it is not shown. Some ideas?
Thanks
What's definition of rect in the code? Despite this uncertainty below snippet should work
final Rectangle canvasSize = document.getPageEffectiveArea(new PageSize(lastPage.getPageSize()));
Canvas c = new Canvas(canvas, pdfOut, canvasSize);
Paragraph paragraph = new Paragraph()
.add(new Text("Este documento foi assinado Hoje"))
.setHeight(canvasSize.getHeight())
.setVerticalAlignment(VerticalAlignment.BOTTOM);

Add footer text and page number in same line on docx file with docx4j java

I am trying to add small text (left side) and page number (right side) on the footer of a .docx document in the same line
so far I can add the text and the page number but in 2 lines
TextVersionv02312
1
But I need it
TextVersionv02312 1
The code that I am using to add text and page number is:
private static Ftr createFooter(WordprocessingMLPackage wordMLPackage, String content, ObjectFactory factory, Part sourcePart, InputStream is) throws IOException, Throwable {
Ftr footer = factory.createFtr();
P paragraph = factory.createP();
R run = factory.createR();
/*
* Change the font size to 8 points(the font size is defined to be in half-point
* size so set the value as 16).
*/
RPr rpr = new RPr();
HpsMeasure size = new HpsMeasure();
size.setVal(BigInteger.valueOf(16));
rpr.setSz(size);
run.setRPr(rpr);
Text text = new Text();
text.setValue(content);
run.getContent().add(text);
paragraph.getContent().add(run);
footer.getContent().add(paragraph);
// add page number
P pageNumParagraph = factory.createP();
addFieldBegin(factory, pageNumParagraph);
addPageNumberField(factory, pageNumParagraph);
addFieldEnd(factory, pageNumParagraph);
footer.getContent().add(pageNumParagraph);
return footer;
}
private static void addPageNumberField(ObjectFactory factory, P paragraph) {
R run = factory.createR();
PPr ppr = new PPr();
Jc jc = new Jc();
jc.setVal(JcEnumeration.RIGHT);
ppr.setJc(jc);
paragraph.setPPr(ppr);
Text txt = new Text();
txt.setSpace("preserve");
txt.setValue(" PAGE \\* MERGEFORMAT ");
run.getContent().add(factory.createRInstrText(txt));
paragraph.getContent().add(run);
}
I have been thinking to add a table or something like that on the footer to put the elements in the same line, But it seems that I am overcomplicating the stuff.
or maybe I can append the page number to the text paragraph
what do you think?
thanks in advance!
You can do it any way you can in Word, for example, with tab stops. (Or as you say, tables, but I'd use say a centre aligned then a right aligned tab if you wanted centre then right)
Easiest is to get it right in Word, then use the docx4j webapp or Docx4j Helper Word AddIn, to generate corresponding Java code from that sample document.

How to prevent first chapter on page two when table in header of pdf generated with iText?

When having a PdfPTable in the header of the document, the first Chapter added gets added too page two, leaving the first page blank. If having just text in the header all works fine (see the out commented line in code sample). Am I doing something wrong or are there a workaround for this problem? I'm using iText-2.1.7.
So to be clear: The code below generates a pdf with one empty page as the first page and if going with the out commented row instead there is no empty page first.
Another thing is that if having a table in the header the generated header gets no height making the text of the document placed over the header table. That one I can work around. But it could perhaps give some help in understanding what's happening...
Document vDocument = new Document();
PdfWriter.getInstance(vDocument, new FileOutputStream("C:/Test.pdf"));
PdfPTable vTable = new PdfPTable(1);
vTable.addCell(new PdfPCell (new Phrase("Header text")));
Phrase vPhr = new Phrase();
vPhr.add(vTable);
HeaderFooter vHeaderFooter = new HeaderFooter(vPhr, false);
// HeaderFooter vHeaderFooter = new HeaderFooter(new Phrase("Header text"), false);
vDocument.setHeader(vHeaderFooter);
vDocument.open();
vDocument.add(new Chapter("New Chapter", 0));
for (int i=0; i<1000; i++) {
vDocument.add(new Paragraph(" TEXT " + i));
}
vDocument.close();

How to extract bold text from pdf using pdfbox?

I am using a Apache pdfbox for extracting text. I can extract the text from pdf but I dont know how to know that whether the word is bold or not??? (code suggestion would be good!!!)
Here is the code for extracting plain text from pdf that is working fine.
PDDocument document = PDDocument
.load("/home/lipu/workspace/MRCPTester/test.pdf");
document.getClass();
if (document.isEncrypted()) {
try {
document.decrypt("");
} catch (InvalidPasswordException e) {
System.err.println("Error: Document is encrypted with a password.");
System.exit(1);
}
}
// PDFTextStripperByArea stripper = new PDFTextStripperByArea();
// stripper.setSortByPosition(true);
PDFTextStripper stripper = new PDFTextStripper();
stripper.setStartPage(1);
stripper.setEndPage(2);
stripper.setSortByPosition(true);
String st = stripper.getText(document);
The result of PDFTextStripper is plain text. After extracting it, therefore, it is too late. But you can override certain methods of it and only let through text which is formatted according to your wishes.
In case of the PDFTextStripper you have to override
protected void processTextPosition( TextPosition text )
In your override you check whether the text in question fulfills your requirements (TextPosition contains much information on the text in question, not only the text itself), and if it does, forward the TextPosition text to the super implementation.
The main problem is, though, to recognize which text is bold.
Criteria for boldness may be the word bold in the font name, e.g. Courier-BoldOblique - you access the font of the text using text.getFont() and the postscript name of the font using the font's getBaseFont() method
String postscriptName = text.getFont().getBaseFont();
Criteria may also be from the font descriptor - you get the font descriptor of a font using the getFontDescriptor method, and a font descriptor has an optional font weight value
float fontWeight = text.getFont().getFontDescriptor().getFontWeight();
The value is defined as
(Optional; PDF 1.5; should be used for Type 3 fonts in Tagged PDF documents) The weight (thickness) component of the fully-qualified font name or font specifier. The possible values shall be 100, 200, 300, 400, 500, 600, 700, 800, or 900, where each number indicates a weight that is at least as dark as its predecessor. A value of 400 shall indicate a normal weight; 700 shall indicate bold.
The specific interpretation of these values varies from font to font.
EXAMPLE 300 in one font may appear most similar to 500 in another.
(Table 122, Section 9.8.1, ISO 32000-1)
There may be additional hints towards bold-ism to check, e.g. a big line width
double lineWidth = getGraphicsState().getLineWidth();
when the rendering mode draws an outline, too:
int renderingMode = getGraphicsState().getTextState().getRenderingMode();
You may have to try with your the documents you have at hand which criteria suffice.

Categories