When I open up my file in my text editor. I am only getting the file's location in the text pane. Am I making a simple mistake somewhere or is there a better way to do this? Should I use an ArrayList to store the images locations?
Example of what is happening: I have a file that has two lines...
C:\...\pic.png
(picture description)
When I try to open up the file (after I save it in the text editor) it shows the actual location of the picture. I want to be able to use BufferedImage to get the directory and add the image to the JTextPane. Otherwise (if the text isn't a location), simply add the text to the text pane.
FYI: textArea is of type JTextPane
Code that opens my file
// sb is my StringBuffer
try
{
b = new BufferedReader(new FileReader(filename));
String line;
while((line=b.readLine())!=null)
{
if (line.contains("C:\\...\\Pictures\\"))
{
BufferedImage image = ImageIO.read(new File(line));
ImageIcon selectedPicture = new ImageIcon(image);
textArea.insertIcon(selectedPicture);
}
sb.append(line + "\n");
textArea.setText(sb.toString());
}
b.close();
}
If you have any questions about this code or need clarification, don't hesitate to ask.
OK. The way you are setting content on to the JTextPane is incorrect.
The basic trick is to get StyleDocument out of the JTextPane and then set a Style on the document. A style basically explains how the component needs to be rendered. For example, text formatting, image icons, spacing etc.
Given that following code will get you started.
JTextPane textPane = new JTextPane();
try {
BufferedReader b = new BufferedReader(
new FileReader("inputfile.txt"));
String line;
StyledDocument doc = (StyledDocument) textPane.getDocument();
while ((line = b.readLine()) != null) {
if (line.contains("/home/user/pictures")) {
Style style = doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(line));
doc.insertString(doc.getLength(), "ignore", style);
} else {
Style textStyle = doc.addStyle("StyleName", null);
//work on textStyle object to get required color/formatting.
doc.insertString(doc.getLength(), "\n" + line, textStyle);
}
}
b.close();
} catch (Exception e) {
e.printStackTrace();
}
Related
I have a service that replaces the placeholders of some given word document. And I have some properties that give me information about what should be in the placeholder.
I use Apache Poi to set new text to word document.
for (XWPFParagraph paragraph : paragraphList) {
for (XWPFRun run : paragraph.getRuns()) {
// for example if run has placeholder ${topicData:labelEn}
// i just set new text for it
run.setText(properties[placeholder], 0);
}
}
So replacing text with text is not a problem.
But now i want to add new placeholder ${qr:size}, which replaces this text with qr image generated by my qr generator function in XWPFRun, so my problem is how can I replace text with image using apache poi, so that the top left coordinates of the image start at position ${qr:size}.
Please don't forget that i am not asking about replacing image to image. I already know how to do that. I am interested in replacing text with an image.
private void replaceTextWithImage(XWPFRun run, int size) {
BufferedImage qrCodeImage = printVersionService.generateQRCodeImage("QR TEXT");
File imageFile = new File("image.jpg");
try {
ImageIO.write(qrCodeImage, "jpg", imageFile);
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream is = new FileInputStream(imageFile);
run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, "QR TEXT", Units.toEMU(size), Units.toEMU(size));
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
}
run.setText("", 0);
}
I am having html content store as a raw string in my database and I like to print it in pdf, but with custom size, for example page size to be 10cm width and 7 com height, not standard A4 format.
Can someone gives me some examples if it is possible.
ByteArrayOutputStream out = new ByteArrayOutputStream();
PDRectangle rec = new PDRectangle(recWidth, recHeight);
PDPage page = new PDPage(rec);
try (PDDocument document = new PDDocument()) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.defaultTextDirection(BaseRendererBuilder.TextDirection.LTR);
String htmlContent = "<b>Hello world</b>" + content;
builder.withHtmlContent(htmlContent, "");
document.addPage(page);
builder.usePDDocument(document);
PdfBoxRenderer renderer = builder.buildPdfRenderer();
renderer.createPDFWithoutClosing();
document.save(out);
} catch (Exception e) {
ex.printStackTrace();
}
return new ByteArrayInputStream(out.toByteArray());
This code generates for me 2 files, one small and one A4.
UPDATE:
I tried this one:
try (PDDocument document = new PDDocument()) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.defaultTextDirection(BaseRendererBuilder.TextDirection.LTR);
builder.useDefaultPageSize(210, 297, PdfRendererBuilder.PageSizeUnits.MM);
builder.usePdfAConformance(PdfRendererBuilder.PdfAConformance.PDFA_3_A);
String htmlContent = "<b>content</b>";
builder.withHtmlContent(htmlContent, "");
builder.usePDDocument(document);
PdfBoxRenderer renderer = builder.buildPdfRenderer();
renderer.createPDFWithoutClosing();
document.save(out);
} catch (Exception e) {
log.error(">>> The creation of PDF is invalid!");
}
But in this case content is not shown, if I remove useDefaultPageSize, content will be shown
I didn't check this solution before, but try initialise the builder object with your desired page size and document type like below
builder.useDefaultPageSize(210, 297, PdfRendererBuilder.PageSizeUnits.MM);
builder.usePdfAConformance(PdfRendererBuilder.PdfAConformance.PDFA_3_A);
the lib include many PDF format next is PdfAConformance Enum with possible values
PdfAConformance Enum
I want to add an image which is retrieved from the mysql db and print it on a pdf file in iText java. The image retrieved from the db is stored in the lblimg. How do I achieve that in java ?
Here's my partial code:
String filename = null;
int s = 0;
byte[] person_img = null;
uploadbtn = new JButton("Upload a Photo");
uploadbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
try{
File img = new File(filename);
FileInputStream fis = new FileInputStream(img);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for(int readNum; (readNum = fis.read(buf)) != -1;){
bos.write(buf, 0, readNum);
}
person_img = bos.toByteArray();
fis.close();
}catch(Exception e1){
e1.printStackTrace();
}
}
});
// Partial code for adding image to db
stt.setBytes(8, person_img);
// Partial codes for retrieving image from db
byte[] imageData = rs.getBytes("Image");
format = new ImageIcon(imageData);
lblimg.setIcon(format);
//Creating the document and adding the lblimg (which contains the image retrieved from the db). PLEASE HELP HERE. I CANNOT ADD THE IMAGE TO PDF document.
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("Report.pdf"));
doc.open();
doc.add(new Paragraph( // img to be added here ));
Update 1 by Bruno Lowagie
Snippet taken from the full code:
try {
Image i = Image.getInstance((PdfTemplate) lblimg.getIcon());
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("Report.pdf"));
doc.open();
Image img = Image.getInstance("ja.png");
doc.add(img);
doc.add(i);
doc.add(new Paragraph("Employee Information", FontFactory.getFont(FontFactory.TIMES_BOLD,18, Font.BOLD, BaseColor.RED)));
doc.add(new Paragraph("______________________________________________________________________________"));
doc.add(new Paragraph("Employee ID is " + val1));
doc.add(new Paragraph("First Name is " + val2 + "\t\t" + " Last Name is " + val3));
doc.add(new Paragraph("Job Position " + val4));
doc.add(new Paragraph("Allowances allowed " + val5));
doc.add(new Paragraph("Salary " + val10));
JOptionPane.showMessageDialog(null, "Report Saved");
doc.close();
} catch(Exception e1) {
e1.printStackTrace();
}
As getIcon returns a javax.swing class and as PdfTemplate is an iText class extending the PdfContentByte class that contains a ByteBuffer of PDF syntax, a ClassCastException is thrown here: (PdfTemplate) lblimg.getIcon()
Update 2 by Bruno Lowagie
The actual question was posted as a comment: How do I retrieve an image which is in a JLabel and add it on a PDF? This question is answered in update 3 of my answer.
Assuming that this contains an image:
byte[] imageData = rs.getBytes("Image");
In other words: assuming that imageData is a valid JPEG, JPEG2000, GIF, PNG, BMP, WMF, TIFF or JBIG2 image, then you can create a com.itextpdf.text.Image object like this:
Image img = Image.getInstance(imageData);
Once you have this img instance, you can add it to the document like this:
document.add(img);
I don't understand why you'd create an ImageIcon instance. Nor is it clear why you refer to a Paragraph object.
Update 1:
Now that I see your full code, I see a very strange line:
Image i = Image.getInstance((PdfTemplate) lblimg.getIcon());
You are casting a javax.swing object to an iText object. This can never work. You should get a ClassCastException at this point in your code.
I also see that you know how to add an image from a file:
Image img = Image.getInstance("ja.png");
doc.add(img);
When you don't have a path to a file, the fastest way you'll find alternative getInstance() methods, is by consulting the Javadoc API documentation: http://api.itextpdf.com/itext/com/itextpdf/text/Image.html#getInstance(byte[])
Update 2:
I have updated the question so that it contains the relevant code. As explained in my answer (that unfortunately wasn't accepted), the following line throws a ClassCastException:
Image i = Image.getInstance((PdfTemplate) lblimg.getIcon());
This exception is caught like this:
} catch(Exception e1) {
e1.printStackTrace();
}
Hence all the code starting with the following line is skipped:
Document doc = new Document();
As a result, no document is created. This is not an iText problem. This is a case of bad exception handling.
Update 3:
Finally, the real question is asked in a comment: In simple words: How to I retrieve an image which is in a JLabel and add it on a PDF?
Again it turns out that I have already answered that question. I referred to the Javadoc API documentation for the Image class. We find the following getInstance() method: http://api.itextpdf.com/itext/com/itextpdf/text/Image.html#getInstance(java.awt.Image, java.awt.Color)
In other words, we can create an iText Image object using a Java Image object. You have the following line in your code:
ImageIcon format = new ImageIcon(imageData);
Or, in your case, you could try something like:
ImageIcon format = (ImageIcon)lblimg.getIcon();
You can get a java.awt.Image object from this ImageIcon like this:
java.awt.Image awtImage = format.getImage();
As per the iText API documentation, you can create an iText image like this:
Image img = Image.getInstance(awtImage, null);
I am trying to convert a .txt file into a .pdf file using iText library.
The problem that I am facing is the following:
I have a clear formatting in the txt file, something similar with this:
TEXT *******************
Other text here * SOME_CODE_HERE_ *
Other text *******************
And in the output the formatting is gone and looks like this:
TEXT ******************
Other text here * SOME_CODE_HERE_ *
Other text ******************
The code looks like this:
public static boolean convertTextToPDF(File file) throws Exception {
BufferedReader br = null;
try {
Document pdfDoc = new Document(PageSize.A4);
String output_file = file.getName().replace(".txt", ".pdf");
System.out.println("## writing to: " + output_file);
PdfWriter.getInstance(pdfDoc, new FileOutputStream(output_file)).setPdfVersion(PdfWriter.VERSION_1_7);;
pdfDoc.open();
Font myfont = new Font();
myfont.setStyle(Font.NORMAL);
myfont.setSize(11);
pdfDoc.add(new Paragraph("\n"));
if (file.exists()) {
br = new BufferedReader(new FileReader(file));
String strLine;
while ((strLine = br.readLine()) != null) {
Paragraph para = new Paragraph(strLine + "\n", myfont);
para.setAlignment(Element.ALIGN_JUSTIFIED);
pdfDoc.add(para);
}
} else {
System.out.println("no such file exists!");
return false;
}
pdfDoc.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null)
br.close();
}
return true;
}
I also tried to create a BaseFont with IDENTITY_H but it doesn't work.
I guess it's about the encoding or something like that.
What do you think? I run out of solutions...
Thanks
LE:
As suggested by Alan, and by the tutorial from iText's page, I used this part in addition with my existing code and it works fine.
BaseFont courier = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.EMBEDDED);
Font myfont = new Font(courier);
You need to use a Monospaced Font e.g. Courier.
http://en.wikipedia.org/wiki/Monospaced_font
http://itextpdf.com/examples/iia.php?id=208
I know this is old, but i had the same problem in converting text files into pdf's and i used this (i wrote this in vb.net):
Dim pdfDoc As Document = New Document(PageSize.A4)
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream(pdfFoldername & "\" & "name of file", FileMode.Create))
pdfDoc.Open()
Dim courier As BaseFont = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.EMBEDDED)
Dim myfont As iTextSharp.text.Font = New iTextSharp.text.Font(courier, 10)
Dim para As Paragraph = New Paragraph(page, myfont)
pdfDoc.Add(para)
The difference to the above answer and updated code is using '10' as my font size. That made the PDF look identical to the formatting from the text file.
In order to get beautiful result, you should use a PDF generating library supporting "Word-like" tabulation (left, right and center) by absolute position in points or percent.
Here I used PDFFlow library to move text to the exact position (for example, text "(Name)" is placed at the position 80% from left page side):
DocumentBuilder
.New()
.AddSection()
.AddParagraph()
// Create a line from X=0 to X=20%:
.AddTabSymbol().AddTabulationInPercent(20, TabulationType.Right, TabulationLeading.BottomLine)
// Create a line from X=60% to X=100%:
.AddTabSymbol().AddTabSymbol().AddTabulationInPercent(60).AddTabulationInPercent(100, TabulationType.Right, TabulationLeading.BottomLine)
.ToSection()
.AddParagraph()
// Add text under the first line in the center (position 10%):
.AddTabSymbol().AddTextToParagraph("(Date)").AddTabulationInPercent(10, TabulationType.Center)
// Add text under the second line in the center (position 80%):
.AddTabSymbol().AddTextToParagraph("(Name)").AddTabulationInPercent(80, TabulationType.Center)
.ToDocument().Build("Result.pdf");
You can also set tabulation in points. But in case you need to change PaperSize and Orientation dynamically, better to use percent, and the library will calculate position in points automatically.
Here is a tutorial with more examples: Adding Tabulation to PDF.
I'm reading some text from a .txt file and writing those to a pdf file.But in my pdf the texts are showing as some bigger fonts. Even though I've changed the font size of the .txt file to bigger or too small the fonts in pdf will be same.
Part of my code which is working with reading writing in text file
Document document = new Document(PageSize.A4.rotate(), 36, 36, 80, 160);
........
.........
document.newPage();
//Writing in a default page from the txt file
document.add(new com.lowagie.text.Paragraph("\n"));
iStream = new FileInputStream(path1); //path1 is location of .txt file
in = new DataInputStream(iStream);
is = new InputStreamReader(in);
br = new BufferedReader(is);
String strLine;
while ((strLine = br.readLine()) != null)
{
Paragraph para = new com.lowagie.text.Paragraph(strLine + "\n");
para.setAlignment(Element.ALIGN_JUSTIFIED);
document.add(new com.lowagie.text.Paragraph(strLine + "\n"));
}
br.close();
is.close();
in.close();
iStream.close();
document.close();
writer.close();
Sorry I'm using the lower version of itext because right now I can't add any third party library to my windchill.This version of itext already my windchill have in it.
How to set the font size inside pdf file when writing into it.?Any help would be really helpful.
Quite simple :D
Fist, i would change one thing:
while ((strLine = br.readLine()) != null) {
Paragraph para = new com.lowagie.text.Paragraph(strLine + "\n");
para.setAlignment(Element.ALIGN_JUSTIFIED);
document.add(para);
}
This way, the paragraph is justified in the document. The way you did it, you changed the text alignment of one paragaph-object, but then added a new, totally different one to the PDF.
Now to your problem:
You can specify the Font in each Paragraph` contructor as follows:
Paragraph para = new com.lowagie.text.Paragraph(strLine + "\n", FontFactory.getFont("Arial", 14f /*This is the size, but as a float!*/);
The entire documentation of the lowagie API can be found here.
Best Regards