I want to create a PDF using image and some text. here image used as mask and text set on different spatial place.
I already generate pdf using image but cannot write text on it.
Here is the image
And output
My code
import com.itextpdf.text.*;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import javax.swing.JFileChooser;
public class Test {
public static void main(String[] args) {
Document document = new Document(PageSize.A4_LANDSCAPE, 0, 0, 0, 0);
String input = "src/icon/orginal_pad.jpg"; // .gif and .jpg are ok too!
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
String filePath = fileChooser.getSelectedFile().getPath();
try {
FileOutputStream fos = new FileOutputStream(filePath);
PdfWriter writer = PdfWriter.getInstance(document, fos);
writer.open();
document.open();
Image im = Image.getInstance(input);
im.scaleToFit(PageSize.A4_LANDSCAPE.getWidth(), PageSize.A4_LANDSCAPE.getHeight());
document.add(im);
//code here
document.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Related
I have written a program (collecting from various sources, I am a beginner) in Java that takes a text(bengali) written in a .txt file and converts it to a .bmp image using the drawString function. The code is :
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.util.*;
import java.awt.font.*;
import java.awt.geom.*;
class TextToImageDemo
{
public static void main(String[] args) throws IOException
{
String sampleText = "আমার",s="নাম";
BufferedReader br = null;
for (int u=1;u<=9;u++)
{
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E:\\Java\\bengtext\\f2-0"+u+".txt")),"UTF-8"));
while ((sampleText = br.readLine()) != null)
{
System.out.println(sampleText);
s=sampleText;
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
//Image file name
String fileName = "Image";
//create a File Object
File newFile= new File("./" + fileName + ".jpeg");
//create the font you wish to use
Font font = new Font(/*Lohit Bengali*/"Kalpurush", Font.PLAIN, 50);
//create the FontRenderContext object which helps us to measure the text
FontRenderContext frc = new FontRenderContext(null, true, true);
//create a BufferedImage object
BufferedImage image = new BufferedImage(2000, 200, BufferedImage.TYPE_INT_RGB);
//calling createGraphics() to get the Graphics2D
Graphics2D g = image.createGraphics();
System.out.println(s);
//set color and other parameters
g.setColor(Color.WHITE);
g.fillRect(0, 0, 2000, 200);
g.setColor(Color.BLACK);
g.setFont(font);
FontMetrics fm=g.getFontMetrics();
Rectangle r=new Rectangle(fm.getStringBounds(s, g).getBounds());
String d=s.substring(1,s.length());
g.drawString(d, image.getWidth()/2-r.width/2, image.getHeight()/2+r.height/2);
//releasing resources
g.dispose();
try
{
FileOutputStream fos = new FileOutputStream("E:\\Java\\bengtext\\f2-0"+u+".bmp");
ImageIO.write(image,"bmp",fos);
fos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}
My main problem lies in the fact that a text like
দ্বিতীয়তা , একাগ্রতা , " জ্ঞান আহরনের একটি মাত্র উপায়
is formed like
How can this be solved?
Edit:
On checking all the 263 fonts available , I found only 6 of them were able to display bengali somewhat correctly. But in everyone of them the problem with the joint words lie as shown in the above picture. So question is : What is the exact problem happening here? Is JAVA not being able to read the joint words correctly, or is it not being able to draw them correctly ?
And secondly , how to make java draw the joint words correctly?
I'm working on a project and the goal is to have all images read with ImageIO. This seems to work for everything except GIF images (which display as a static image of the initial frame). I have seen other answers on Stack Overflow and from a thread on the Oracle forums but most require using Java's File class which I can't access due to the program's SecurityManager. I've been able to break the GIF down into an Image array and edit the metadata, but after stitching everything back together I can only display a single image.
Below is a SSCCE for the program:
import java.awt.Image;
import java.awt.Toolkit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GifRenderer {
public static void main(String[] args) throws Exception {
Image image = null;
byte[] imageByteArray = null;
try {
String location = "http://i.imgur.com/Ejh5gJa.gif";
imageByteArray = createByteArray(location);
// This works, but I'm trying to use ImageIO
//image = Toolkit.getDefaultToolkit().createImage(imageByteArray);
InputStream in = new ByteArrayInputStream(imageByteArray);
image = ImageIO.read(in);
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
frame.setSize(300, 300);
JLabel label = new JLabel(new ImageIcon(image));
frame.add(label);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// Constraint: This method simulates how the image is originally received
private static byte[] createByteArray(String urlString) throws IOException {
URL url = new URL(urlString);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096];
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (is != null) { is.close(); }
}
return baos.toByteArray();
}
}
Some constraints worth mentioning that might not be clear:
The image is originally received as a byte array
The image should be read by ImageIO
The final result should be an Image object
The File class can't be accessed
Given these constraints is there still a way to use ImageIO to display the GIF the same way Toolkit.getDefaultToolkit().createImage() would display the image?
I am trying to save a resized picture to the user's desktop but not sure how to do that.
Here's my code so far:
mi.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String userhome = System.getProperty("user.home");
fileChooser = new JFileChooser(userhome + "\\Desktop");
fileChooser.setAutoscrolls(true);
switch (fileChooser.showOpenDialog(f)) {
case JFileChooser.APPROVE_OPTION:
BufferedImage img = null;
try {
img = ImageIO.read(fileChooser.getSelectedFile());
} catch (IOException e1) {
e1.printStackTrace();
}
Image dimg = img.getScaledInstance(f.getWidth(),
f.getHeight(), Image.SCALE_SMOOTH);
path = new ImageIcon(dimg);
configProps.setProperty("Path", fileChooser
.getSelectedFile().getPath());
imBg.setIcon(path);
break;
}
}
});
The code above resizes the imaged selected to fit the size of the JFrame then sets it to the JLabel.
This all works well but I also want to output the file to a set location lets say to the users desktop to make it easier. I'm currently looking at output stream but can't quite get my head around it.
Any help would be great.
Get the current Icon from the JLabel...
Icon icon = imgBg.getIcon();
Paint the icon to a BufferedImage...
BufferedImage img = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
Save the image to a file...
ImageIO.write(img, "png", new File("ResizedIcon.png"));
(and yes, you could use a JFileChooser to pick the file location/name)
You should also take a look at this for better examples of scaling an image, this way, you could scale the BufferedImage to another BufferedImage and save the hassle of having to re-paint the Icon
You might also like to take a look at Writing/Saving an Image
This is a example which is about saving images from Web to the local.
package cn.test.net;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageRequest {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
//a url from web
URL url = new URL("http://img.hexun.com/2011-06-21/130726386.jpg");
//open
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//"GET"!
conn.setRequestMethod("GET");
//Timeout
conn.setConnectTimeout(5 * 1000);
//get data by InputStream
InputStream inStream = conn.getInputStream();
//to the binary , to save
byte[] data = readInputStream(inStream);
//a file to save the image
File imageFile = new File("BeautyGirl.jpg");
FileOutputStream outStream = new FileOutputStream(imageFile);
//write into it
outStream.write(data);
//close the Stream
outStream.close();
}
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
//every time read length,if -1 ,end
int len = 0;
//a Stream read from buffer
while( (len=inStream.read(buffer)) != -1 ){
//mid parameter for starting position
outStream.write(buffer, 0, len);
}
inStream.close();
//return data
return outStream.toByteArray();
}
}
Hope this is helpful to you!
I have a html file which has image in binary form.
I want to convert that to pdf using java.
Can anyone please help me with this?
And the Html file contains Base64 image file
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.text.Chunk;
public class Test{
public static void main(String args[]){
try {
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Test.pdf"));
// step 3
document.open();
document.newPage();
document.add(new Chunk(""));
// step 4
XMLWorkerHelper.getInstance().parseXHtml(writer, document,new FileInputStream("/home/farheen/workspace/html.to.pdf/test.html"));
//step 5
document.close();
System.out.println( "PDF Created!" );
}catch (Exception e) {
e.printStackTrace();
}
}
}
You can use itext
With this example code from here
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class ImageExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Image.pdf"));
document.open();
Image image1 = Image.getInstance("watermark.png");
document.add(image1);
String imageUrl = "http://jenkov.com/images/" +
"20081123-20081123-3E1W7902-small-portrait.jpg";
Image image2 = Image.getInstance(new URL(imageUrl));
document.add(image2);
document.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
I am using iText and some SVG rendering library.
I want to render a SVG image to PDF. I am using following code to do that. Now the problem is I am giving an area chart SVG to it, it is not rendering line properly. Attaching screenshots.
Following classes has been used:
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.DocumentLoader;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.svg.SVGDocument;
and here the cop snippet:
String parser = XMLResourceDescriptor.getXMLParserClassName();
factory = new SAXSVGDocumentFactory(parser);
UserAgent userAgent = new UserAgentAdapter();
DocumentLoader loader = new DocumentLoader(userAgent);
ctx = new BridgeContext(userAgent, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
builder = new GVTBuilder();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate chartImageTemplate = cb.createTemplate(1000, 1000);
SVGDocument svgDoc=null;
try {
InputStream in = new ByteArrayInputStream(chartImage.getBytes());
svgDoc = factory.createSVGDocument("", in);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
GraphicsNode mapGraphics = builder.build(ctx, svgDoc);
DefaultFontMapper mapper = new DefaultFontMapper();
PdfGraphics2D g2 = (PdfGraphics2D)cb.createGraphics(1000, 500, mapper);
Graphics2D g2d = g2;
mapGraphics.paint(g2d);
g2d.dispose();
cb.addTemplate(chartImageTemplate, 0, 0);
return mapGraphics.getGeometryBounds().getHeight();
}catch(Exception e){
}
You can find SVG here:
http://speedy.sh/xvDp8/demo.svg
Actual SVG:
Rendered PDF