Printing good characters into bad characters unknown characters - java

PDF files contain some French accent characters such as: e with some tick markt on top of them same with u or so.
When i check the PDF files before printing, i can see they are absolutely correct, i can read them in that PDF, i can zoom in and copy them perfectly fine.
But the moment Java touch it and prints it. Everything just does not work as it suppose to be.
How can i fix it please? the cloud version of that PDF is perfect but once my following code use to handle the file, then all those characters become broken in the print copy.
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaTray;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
public class PrintA4 {
public static boolean saveFile(URL url, String file) throws IOException {
boolean download_status = false;
System.out.println("open");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(new File(file));
System.out.println("reading file...");
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
download_status = true;
System.out.println("downloaded");
return download_status;
}
public static void main(String[] args) throws IOException, PrinterException {
String downloaded_filename = "C:/pdf.pdf";
String download_pdf_from = "http://www.example.com/1.pdf" ;
String downloaded_filename_open_as_pdf = "C:\\pdf.pdf";
String printerNameDesired = "Brother HL-6180DW series";
PrintService[] services = PrinterJob.lookupPrintServices();
DocPrintJob docPrintJob = null;
for (int i = 0; i < services.length; i++) {
System.out.println(services[i]);
}
try{
URL url = new URL(download_pdf_from);
if(saveFile(url, downloaded_filename)) {
try {
PDDocument pdf = PDDocument.load(new File(downloaded_filename_open_as_pdf));
PrinterJob job = PrinterJob.getPrinterJob();
for (int i = 0; i < services.length; i++) {
if (services[i].getName().equalsIgnoreCase(printerNameDesired)) {
docPrintJob = services[i].createPrintJob();
}
}
job.setPrintService(docPrintJob.getPrintService());
job.setPageable(new PDFPageable(pdf));
PrintRequestAttributeSet pset = new HashPrintRequestAttributeSet();
pset.add(MediaTray.BOTTOM);
job.print(pset);
} catch (Exception e) {
System.out.println("[FAIL]");
}
} else {
System.out.println("[FAIL]");
}
} catch (Exception ae) {
System.out.println("[FAIL]");
}
}
}

Related

How I can create TOC using apache poi

I have the code which create table of content like this:
image screenshot ,
but i want resualt like this:
image screenshot ,
and this is my code
package com.example;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.dump.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField;
These are libraries which I'm using for this project
and I'm also using the maven package manager
public class toc {
public static void main(String[] args) throws IOException, OpenXML4JException {
XWPFDocument docTemplate = null;
try {
File file = new File(
"outfile02.docx"); // "C:\\Reports\\Template.docx";
FileInputStream fis = new FileInputStream(file);
docTemplate = new XWPFDocument(fis);
generateTOC(docTemplate);
saveDocument(docTemplate);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (docTemplate != null) {
docTemplate.close();
}
}
}
save function
private static void saveDocument(XWPFDocument docTemplate) throws FileNotFoundException, IOException {
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream("outfile03.docx");
docTemplate.write(outputFile);
} finally {
if (outputFile != null) {
outputFile.close();
}
}
}
TOC generator function
public static void generateTOC(XWPFDocument document)
throws InvalidFormatException, FileNotFoundException, IOException {
String findText = "${TOC}";
String replaceText = "";
for (XWPFParagraph p : document.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
int pos = r.getTextPosition();
String text = r.getText(pos);
if (text != null && text.contains(findText)) {
text = text.replace(findText, replaceText);
r.setText(text, 0);
addField(p, "TOC \\o \"1-3\" \\h \\z \\u");
break;
}
}
}
}
and this is last function
private static void addField(XWPFParagraph paragraph, String fieldName) {
CTSimpleField ctSimpleField = paragraph.getCTP().addNewFldSimple();
// ctSimpleField.setInstr(fieldName + " \\h ");
ctSimpleField.setInstr(fieldName);
ctSimpleField.addNewR().addNewT().setStringValue("outfile03.docx");
}
}

Create Zip File on Disk from Memory File

First of all, Please Pardon me for Poor Coding!
Requirement:
1. Create xls/xlsx Report in Memory from Database ResultSet (ie. Plain Text File should not be written to Disk).
2.Create ZIP on Disk From the xlsx file in Memory.
Environment:
WinXP SP2, JDK1.6_06, Zip4j1.3.1, poi3.8
I am using Apache's POI and Zip4j and am following Mr.Shrikant's Example published at "http://www.lingala.net/zip4j/forum/index.php?topic=257.0"
Observations:
1. This program Writes 27,842 bytes xlsx file to disk for sample data.
2. The same Workbook Creates ByteArrayOutputStream,baoStream of size is 49022bytes
3. After Encryption and Zipping It Creates File of Size 43,084 bytes.
4. While Extracting Zip file,
a) WinZip, throws Error "UnExpected End of File"
b) Winrar, throws "CRC Error"
Please correct me, wherever I am wrong and improve, wherever I am poor!
Thanks in Advance!
package zipconversion;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import net.lingala.zip4j.io.ZipOutputStream;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ZipCreationInMemory {
ZipOutputStream zos = null;
XSSFWorkbook workbook = null;
ByteArrayOutputStream baoStream = null;
String path = null;
String xlsxfileExtn = null;
String zipfileExtn = null;
String onlyFileName = null;
String xlsxFileName = null;
String zipFileName = null;
String xlsxFilePath = null;
String zipFilePath = null;
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public void createXlsxFile() {
try {
SimpleDateFormat timeFormat = new SimpleDateFormat("hh_mm_ss");
path = "D:\\abcd\\";
xlsxfileExtn = ".xlsx";
zipfileExtn = ".zip";
onlyFileName = "ReportData_".concat(timeFormat.format(new Date()));
xlsxFileName = onlyFileName + xlsxfileExtn;
zipFileName = onlyFileName + zipfileExtn;
xlsxFilePath = path + xlsxFileName;
zipFilePath = path + zipFileName;
FileOutputStream out = new FileOutputStream(new File(xlsxFilePath));
workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Report");
XSSFRow rowHead = sheet.createRow((short) 0);
XSSFCellStyle headStyle = workbook.createCellStyle();
XSSFFont headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(new XSSFColor(new java.awt.Color(255, 0, 0)));
headStyle.setFont(headerFont);
headStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255)));
headStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
XSSFCellStyle oddStyle = workbook.createCellStyle();
oddStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(randInt(125, 255), randInt(125, 255), randInt(125, 255))));
oddStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
//JDBC CONFIGURATIONS
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
String dbURL = "jdbc:derby://localhost:1527/DATABASE_NAME;create=true;user=USER_ID;password=PASSWORD";
Connection connection = DriverManager.getConnection(dbURL);
Statement st = connection.createStatement();
ResultSet resultSet = st.executeQuery("Select * from TABLE_NAME");
ResultSetMetaData metaData = resultSet.getMetaData();
int colCount = metaData.getColumnCount();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
for (int curColIndx = 0; curColIndx < colCount; curColIndx++) {
XSSFCell cell = rowHead.createCell((short) curColIndx);
cell.setCellStyle(headStyle);
cell.setCellValue(metaData.getColumnName(curColIndx + 1));
}
int index = 1;
while (resultSet.next()) {
XSSFRow row = sheet.createRow((short) index);
for (int curColIndx = 0; curColIndx < colCount; curColIndx++) {
XSSFCell cell = row.createCell((short) curColIndx);
if (index % 2 == 1) {
cell.setCellStyle(oddStyle);
}
else {
cell.setCellStyle(evenStyle);
}
int type = metaData.getColumnType(curColIndx + 1);
if (type == Types.TIMESTAMP) {
cell.setCellValue(sdf.format(resultSet.getDate(curColIndx + 1)));
} else if (type == Types.VARCHAR || type == Types.CHAR) {
cell.setCellValue(resultSet.getString(curColIndx + 1));
} else {
cell.setCellValue(resultSet.getLong(curColIndx + 1));
}
}
index++;
}
baoStream = new ByteArrayOutputStream();
try {
//This Writes 27,842 bytes xlsx file to disk for sample data.
workbook.write(out);
//same workbook is written to ByteArrayOutputStream()
workbook.write(baoStream);
//But, baoStream size is 49022bytes and After Encryption and Zipping It Creates File of Size 43,084 bytes.
System.out.println("baoStream.size() :" + baoStream.size());
try {
//byte[] bytesToWrite = getBytesFromFile();
byte[] bytesToWrite = baoStream.toByteArray();
InMemoryOutputStream inMemoryOutputStream = new InMemoryOutputStream();
zos = new ZipOutputStream(inMemoryOutputStream);
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
parameters.setFileNameInZip(xlsxFileName);
parameters.setSourceExternalStream(true);
zos.putNextEntry(null, parameters);
zos.write(bytesToWrite);
zos.closeEntry();
zos.finish();
zos.close();
// Write contents in our InMemoryOutputStream to a zip file to test if this worked
writeContentsToZipFile(inMemoryOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
out.close();
resultSet.close();
connection.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("Exception is :" + e.toString());
}
}
public ZipCreationInMemory() {
//testZipCreationInMemory();
createXlsxFile();
}
package zipconversion;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Writes the content to memory.
*
*/
public class InMemoryOutputStream extends OutputStream {
// As we cannot know the size of the zip file that is being created,
// we cannot maintain a byte array. We will copy all the bytes that
// gets passed in the write() method to a List. Once all writing is done,
// we can create a byte array from this List and this will be the content
// of the zip file
private List byteList;
// flag to keep track if the outputstream is closed
// no further write operations should be performed once this stream is closed
private boolean closed;
public InMemoryOutputStream() {
byteList = new ArrayList();
closed = false;
}
public void write(int b) throws IOException {
if (closed) {
throw new IOException("trying to write on a closed output stream");
}
byteList.add(Integer.toString(b));
}
public void write(byte[] b) throws IOException {
if (b == null) {
return;
}
write(b, 0, b.length);
}
public void write(byte[] b, int off, int len) throws IOException {
if (closed) {
throw new IOException("trying to write on a closed output stream");
}
if (b != null && len > 0) {
for (int i = 0; i < len; i++) {
byteList.add(Byte.toString(b[i]));
}
}
}
public byte[] getZipContent() {
if (byteList.size() <= 0) {
return null;
}
byte[] zipContent = new byte[byteList.size()+1];
for (int i = 0; i < byteList.size(); i++) {
zipContent[i] = Byte.parseByte((String) byteList.get(i));
}
return zipContent;
}
public void close() throws IOException {
closed = true;
}
}
The bug is possible in method writeContentsToZipFile(inMemoryOutputStream), but you didn't post it's source code...
I think the implement of class InMemoryOutputStream is not required, it's not effective and cause more problem.
If you want to save the zip content to File, replace it with FileOutputStream
If you want to save the zip content in memory, replace it with ByteArrayInputStream inMemoryOutputStream = new ByteArrayInputStream(bytesToWrite.length);
Note: The first parameter of zos.putNextEntry(null, parameters) is null.
It works when parameters.setSourceExternalStream(true). Under this mode, file name and other parameters are supplied via ZipParameters.

How to hide the data between the two tags(<hidden> .. </hidden>) in Word document

I am able to Read the input document using Apache POI and also able to find the data between the tags(What to be hidden) but the problem is i'm unable to write the data in the output file. How can i do the same to write the data and hide it in the output generated file..
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Range;
public class Hidden {
public static void main(String args[]) throws Exception
{
File file = new File("D://me1.doc");
FileInputStream fin = new FileInputStream(file);
FileOutputStream fout = new FileOutputStream("D://Test.doc");
HWPFDocument doc = new HWPFDocument(fin);
Range range = doc.getRange();
WordExtractor extractor = new WordExtractor(doc);
String para[] = extractor.getParagraphText();
String output="";
String hidden="";
for (String p : para) {
String[] w = p.split("[<\\>]");
for(int k=0 ;k<w.length;k++){
if(w[k]!=null && !"".equalsIgnoreCase(w[k])){
if("hidden".equalsIgnoreCase(w[k])){
k++;
CharacterRun run = range.getCharacterRun(k);
hidden= w[k];
k++;
System.out.println(hidden);
run.setVanished(true);
doc.write(fout);
}else{
}
}
}
}
fout.close();
fin.close();
}
}

java.lang.UnsupportedOperationException: Unsupported write variant! at javax.imageio.ImageWriter.unsupported(Unknown Source)

I have been trying to programatically create one png file from a number of other png files in Java using javax.imageio.
In particular I have been trying to use the answer outlined in How do I convert multiple png images to a single tiff file
However when I call the writeInsert(..) method I keep getting the below Exception.
java.lang.UnsupportedOperationException: Unsupported write variant!
at javax.imageio.ImageWriter.unsupported(Unknown Source)
at javax.imageio.ImageWriter.writeInsert(Unknown Source)
I understand that the canInsertImage returns whether it is possible to insert or not (and I can see that this method returns false) however I do not know how to change this.
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
public class ImageTest
{
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException
{
ImageOutputStream ios = null;
ImageWriter writer = null;
try
{
String dirName = "C:/png/test";
File dir = new File(dirName);
if (dir.exists() && dir.isDirectory())
{
File[] files = dir.listFiles();
if (null != files && files.length > 0)
{
File outFile = new File("C:/png", "output.png");
ios = ImageIO.createImageOutputStream(outFile);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("png");
if (null != writers && writers.hasNext())
{
writer = writers.next();
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
for (int i = 0; i < files.length; i++)
{
InputStream fis = null;
try
{
fis = new BufferedInputStream(new FileInputStream(files[i]));
BufferedImage image = ImageIO.read(fis);
IIOImage img = new IIOImage(image, null, null);
if (i == 0)
{
writer.write(null, img, param);
}
else
{
writer.writeInsert(-1, img, param);
}
image.flush();
} finally
{
if (null != fis)
{
fis.close();
}
}
}
}
}
}
} catch (Exception e)
{
System.err.println("OOOps: " + e.getMessage() + "\n");
e.printStackTrace();
} finally
{
if (null != ios)
{
ios.close();
}
if (null != writer)
{
writer.dispose();
}
}
}
}

Prinitng text FIle issue?the long lines of a text file get cut from side?

M using the following code for printing but if there are some long lines in my text file ,they get cut from the sides while printing.What am i doing wrong?
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.OrientationRequested;
public class PrintFileWithSpec {
public static void printFile(String filename,String printerindx){
FileInputStream psStream=null;
int Printerinx=Integer.parseInt(printerindx);
try {
psStream = new FileInputStream(filename);
} catch (FileNotFoundException ffne) {}
if (psStream == null) {
return;
}
DocFlavor psInFormat = null;
int index=filename.lastIndexOf(".");
String extension=filename.substring(index+1);
if(extension.equals("txt"))//||extension.equals("log")||extension.equals("xml")||extension.equals("htm")||extension.equals("html"))
psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
else if(extension.equals("jpg"))
psInFormat = DocFlavor.INPUT_STREAM.JPEG;
else if(extension.equals("png"))
psInFormat = DocFlavor.INPUT_STREAM.PNG;
else if(extension.equals("gif"))
psInFormat = DocFlavor.INPUT_STREAM.GIF;
Doc myDoc = new SimpleDoc(psStream, psInFormat, null);
PrintRequestAttributeSet aset =
new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
aset.add(MediaSizeName.ISO_A4);
//aset.add(Sides.DUPLEX);
aset.add(OrientationRequested.PORTRAIT);
PrintService[] services =
PrintServiceLookup.lookupPrintServices(psInFormat, null);
System.out.println("Printer Selected "+services[Printerinx]);
//PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
DocFlavor[] docFalvor = services[Printerinx].getSupportedDocFlavors();
for (int i = 0; i < docFalvor.length; i++) {
System.out.println(docFalvor[i].getMimeType());
}
if (services.length > 0) {
DocPrintJob job = services[Printerinx].createPrintJob();
try
{
job.print(myDoc, aset);
System.out.print("Printing Doc");
} catch (PrintException pe)
{
System.out.print(pe);
}
}
}
public static void main(String [] args)
{
printFile("D:/testStream.txt","3");
}
}
You have to deal with line wrapping of text files yourself. The javadoc for DocFlavor says:
Furthermore, every Java Print Service instance must fulfill these requirements for processing plain text print data:
The character pair carriage return-line feed (CR-LF) means "go to column 1 of the next line."
A carriage return (CR) character standing by itself means "go to column 1 of the next line."
A line feed (CR) character standing by itself means "go to column 1 of the next line."
*
The client must itself perform all plain text print data formatting not addressed by the above requirements.

Categories