Print ".pdf" file - PrinterJob - java

I'm having problems when trying to print a ".pdf". I printed Strings with this code without problems, but the pdf will not.
My program receives a byte[] with pdf and print it, I thought of recording a tempfile to print from InputStream, but also failed.
Follows the code I'm using to print:
    FileChannel fc = null;
    ByteBuffer bb = ByteBuffer.wrap(pdf);
    FileOutputStream fos = null;
    RandomAccessFile fis = null;
    try {
        File Tempfile = File.createTempFile("portfolios-temp", ".pdf");
        fos = new FileOutputStream(tempfile);
        fos.write(pdf);
        fos.close();
        FileInputStream psStream = new FileInputStream(tempfile);
        DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
        MyDoc doc = new SimpleDoc(psStream, psInFormat, null);
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        aset.add (new Copies (1));
        aset.add (OrientationRequested.PORTRAIT);
        aset.add (Sides.ONE_SIDED);
        aset.add (MediaSizeName.ISO_A4);
        DocPrintJob job printService.createPrintJob =();
        try {
            job.print (myDoc, aset);
        } Catch (Exception pe) {
            pe.printStackTrace ();
        }
    } [...]
I get the Print Service this way:
PrintService printService = null;
for(PrintService printServiceCurrent : PrinterJob.lookupPrintServices()) {
if(printServiceCurrent.getName().equals(PRINTER_NAME)) {
printService = printServiceCurrent;
break;
}
}
He send a command to the printer, but comes like have no content. I checked the temporary file and it is being generated perfectly.
Any idea?
Thanks in advance.

First of all, instead of
PrintRequestAttributeSet aset HashPrintRequestAttributeSet = new();
it should be
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
Second you're not checking the printers that can print the format according to the instructions in the attribute set.
Check this link for more detailed information:
Java Print Service API

Related

Add Image to Document/Template stored on HelloSign using JAVA

USECASE:
I have a document stored on HELLOSIGN which is supposed to be sent to a signer after prepopulating it with some data. Additionally, I have a field in the document where in I should be able to upload the signer image from my DB.
What I have done:
TemplateSignatureRequest request = new TemplateSignatureRequest();
request.setTitle(title);
request.setSubject(emailSubject);
request.setMessage(message);
request.setSigner("ROLE", "<<email_id>>", name);
request.setClientId(CLIENT_ID);
request.setTemplateId(TEMPLATE_ID);
request.setTestMode(true);
request.setCustomFields(customFields);
HelloSignClient client = new HelloSignClient(API_KEY);
client.sendTemplateSignatureRequest(request);
QUESTION : Is there a way I can directly populate the image in the request object by using something like:
request.setDocuments(docs);
Or is there any other way I can achieve this?
Note: I could not mark the image part in the doc as a custom field since I could not find an option to do it on HelloSign
I am trying to replace the Picture section in the image below
The TemplateSignatureRequest extends AbstractRequest which has a function for adding a file
public void addFile(File file) throws HelloSignException {
this.addFile(file, (Integer)null);
}
This was taken from the library. So you can simply use
request.addFile(file);
I reached out to apisupport#hellosign.com to ask them if there is any way to achieve this, and this is the response I got:
"This is currently not available, However, We're always looking for ways to improve HelloSign API and we regularly release new versions of our products with better performance, additional features, and security enhancements. I'll reach out to our product team and pass this idea along as a feature enhancement for them to review to see if this is something we can place on our roadmap"
So, I figured out a work around using PDF stamper
private byte[] stampImageToDoc() throws Exception {
try {
PdfReader pdfReader = new PdfReader(<<template_pdf_path>>);
ByteArrayOutputStream os = new ByteArrayOutputStream();
PdfStamper pdfStamper = new PdfStamper(pdfReader, os);
PdfContentByte cb = pdfStamper.getOverContent(1);
File file = new File(<<imagePath>>);
byte[] imageFile = FileUtils.readFileToByteArray(file);
if (imageFile != null) {
Image image = Image.getInstance(imageFile);
image.scaleAbsoluteHeight(150);
image.scaleAbsoluteWidth(150);
image.setAbsolutePosition(29, 500); //position
cb.addImage(image);
}
pdfStamper.close();
return os.toByteArray();
} catch (DocumentException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
}
Instead of using TemplateSignatureRequest we will be using SignatureRequest and add the stamped doc to send request::
SignatureRequest request = new SignatureRequest();
List<Signer> signers = new ArrayList<>();
Signer signer = new Signer(req.getStudentEmail(), "DME");
signers.add(signer);
request.setTitle(title);
request.setSubject(emailSubject);
request.setMessage(message);
request.setSigners(signers);
request.setClientId(CLIENT_ID);
request.setTestMode(true);
// Image
byte[] docBytes = stampImageToDoc();
List<Document> docs = new ArrayList<>();
Document d = new Document();
File tempFile = new File(<<temporary_path>>);
FileUtils.writeByteArrayToFile(tempFile, docBytes);
d.setFile(tempFile);
docs.add(d);
request.setDocuments(docs);
HelloSignClient client = new HelloSignClient(API_KEY);
client.sendSignatureRequest(request);
Note: This might not be the best solution, but its just a workaround i could think of

Need to know to code printer name in Java

I have use jasper report to create a report in Java and most of the time i tried to setup the printer name by using code, but I couldn't do that. Please help me how to give printer name to print without using print manager
try {
String comname = "";
comname = "Stars Bombay Sweet (Pvt) Ltd.";
JRTableModelDataSource dts = new JRTableModelDataSource(jTable1.getModel());
String path = "D:\\Aster Soft\\Stars Reports\\posh_print\\report1.jrxml";
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", comname);
params.put("para1", InvNo.getText());
params.put("para2", dat);
params.put("para3", Customer.getText());
params.put("credit", jComboBox1.getSelectedItem());
params.put("Qty", GrossQty.getText());
params.put("TotAmont", TotalAmount.getText());
params.put("Discount", Discount.getText());
params.put("GrossAmont", DisAmount.getText());
JasperReport report = JasperCompileManager.compileReport(path);
JasperPrint print = JasperFillManager.fillReport(report, params, dts);
JasperViewer.viewReport(print, false);
JasperPrintManager.printReport(print, true);
} catch (Exception e) {
e.printStackTrace();
}
JasperPrint print = JasperFillManager.fillReport(this.class.getResource("/classpath/yourReport.jasper").getPath(),
new HashMap(), new yourReportDataSource());
PrinterJob job = PrinterJob.getPrinterJob();
/* Create an array of PrintServices */
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
int selectedService = 0;
/* Scan found services to see if anyone suits our needs */
for(int i = 0; i < services.length;i++){
if(services[i].getName().toUpperCase().contains("Your printer's name")){
/*If the service is named as what we are querying we select it */
selectedService = i;
}
}
job.setPrintService(services[selectedService]);
I think below blog link will help you
http://blog.marcnuri.com/choosing-a-printer-programmatically-in-jasper-reports/

Java Printing - Spooling in Printing Queue

I want to print a pdf file to a printer using java-based software specifically Netbeans. When I ran my code below, I saw that the document is in printing queue with a file name "Java Document" with a Spooling status.
The questions are:
I want to know why my printer is not printing the document even if it is in queue?
Is it because of the code or is it because of my printer?
Here is my code:
public String gonnaGo(String newfile) throws FileNotFoundException, PrintException, IOException{
System.out.println("Hello!" + newfile);
InputStream is;
is = new BufferedInputStream(new FileInputStream(newfile)); //The new file will be the one to be printed
Doc doc = new SimpleDoc(in, DocFlavor.INPUT_STREAM.AUTOSENSE,null);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
// Locate the default print service for this environment.
System.out.println("Default printer: " + PrintServiceLookup.lookupDefaultPrintService().getName());
//Check if the file directory of the file to be printed is included
PrintRequestAttributeSet params = new HashPrintRequestAttributeSet(); //ADD PRINTING PROPERTIES HERE
params.add(new Copies(1));
DocPrintJob printJob = service.createPrintJob(); //used to determine whether the print job is finished
printJob.addPrintJobListener(new JobCompleteMonitor());
service.createPrintJob().print(doc, params);
System.out.println("Exiting app");
is.close();
return null;
}
This is the output and it does not print anything. My printer is already connected. I use Canon ip2770 series, Epson Stylus TX117, and HP Deskjet 2510 series with the latest drivers.

Fedex ship label print to Thermal printer using Java

I am using Fedex ship web service to create a shipment. I am using a thermal printer to print the label (Java).
First I wanted to know what should be STOCKTYPE for printing to ZLPII printer, second question follows below.
When printing to the printer and empty label comes out but nothing print, when I use to print to PDF it works very well.
This is my Java code
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.AUTOSENSE, null);
if (pss.length == 0)
System.out.println("FedExSmartPostServiceImpl::saveLabelToFile No printer services available.");
PrintService ps = null;
for (PrintService ps1 : pss) {
if (ps1.getName().indexOf("Zebra") >= 0) {
ps = ps1;
break;
}
}
System.out.println("FedExSmartPostServiceImpl::saveLabelToFile Printing to " + ps);
DocPrintJob job = ps.createPrintJob();
Doc doc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
job.print(doc, null);
fis.close();
Thanks for the help in advance.
I could able to print the label with almost same code as above, with slight change of changing the SimpleDoc as below rather using the FileInputStream.
Doc doc = new SimpleDoc(byteArr, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
Hope this helps.

Open Microsoft Word in Java

I'm trying to open MS Word 2003 document in java, search for a specified String and replace it with a new String. I use APACHE POI to do that. My code is like the following one:
public void searchAndReplace(String inputFilename, String outputFilename,
HashMap<String, String> replacements) {
File outputFile = null;
File inputFile = null;
FileInputStream fileIStream = null;
FileOutputStream fileOStream = null;
BufferedInputStream bufIStream = null;
BufferedOutputStream bufOStream = null;
POIFSFileSystem fileSystem = null;
HWPFDocument document = null;
Range docRange = null;
Paragraph paragraph = null;
CharacterRun charRun = null;
Set<String> keySet = null;
Iterator<String> keySetIterator = null;
int numParagraphs = 0;
int numCharRuns = 0;
String text = null;
String key = null;
String value = null;
try {
// Create an instance of the POIFSFileSystem class and
// attach it to the Word document using an InputStream.
inputFile = new File(inputFilename);
fileIStream = new FileInputStream(inputFile);
bufIStream = new BufferedInputStream(fileIStream);
fileSystem = new POIFSFileSystem(bufIStream);
document = new HWPFDocument(fileSystem);
docRange = document.getRange();
numParagraphs = docRange.numParagraphs();
keySet = replacements.keySet();
for (int i = 0; i < numParagraphs; i++) {
paragraph = docRange.getParagraph(i);
text = paragraph.text();
numCharRuns = paragraph.numCharacterRuns();
for (int j = 0; j < numCharRuns; j++) {
charRun = paragraph.getCharacterRun(j);
text = charRun.text();
System.out.println("Character Run text: " + text);
keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
key = keySetIterator.next();
if (text.contains(key)) {
value = replacements.get(key);
charRun.replaceText(key, value);
docRange = document.getRange();
paragraph = docRange.getParagraph(i);
charRun = paragraph.getCharacterRun(j);
text = charRun.text();
}
}
}
}
bufIStream.close();
bufIStream = null;
outputFile = new File(outputFilename);
fileOStream = new FileOutputStream(outputFile);
bufOStream = new BufferedOutputStream(fileOStream);
document.write(bufOStream);
} catch (Exception ex) {
System.out.println("Caught an: " + ex.getClass().getName());
System.out.println("Message: " + ex.getMessage());
System.out.println("Stacktrace follows.............");
ex.printStackTrace(System.out);
}
}
I call this function with following arguments:
HashMap<String, String> replacements = new HashMap<String, String>();
replacements.put("AAA", "BBB");
searchAndReplace("C:/Test.doc", "C:/Test1.doc", replacements);
When the Test.doc file contains a simple line like this : "AAA EEE", it works successfully, but when i use a complicated file it will read the content successfully and generate the Test1.doc file but when I try to open it, it will give me the following error:
Word unable to read this document. It may be corrupt.
Try one or more of the following:
* Open and repair the file.
* Open the file with Text Recovery converter.
(C:\Test1.doc)
Please tell me what to do, because I'm a beginner in POI and I have not found a good tutorial for it.
First of all you should be closing your document.
Besides that, what I suggest doing is resaving your original Word document as a Word XML document, then changing the extension manually from .XML to .doc . Then look at the XML of the actual document you're working with and trace the content to make sure you're not accidentally editing hexadecimal values (AAA and EEE could be hex values in other fields).
Without seeing the actual Word document it's hard to say what's going on.
There is not much documentation about POI at all, especially for Word document unfortunately.
I don't know : is its OK to answer myself, but Just to share the knowledge, I'll answer myself.
After navigating the web, the final solution i found is :
The Library called docx4j is very good for dealing with MS docx file, although its documentation is not enough till now and its forum is still in a beginning steps, but overall it help me to do what i need..
Thanks 4 all who help me..
You could try OpenOffice API, but there arent many resources out there to tell you how to use it.
You can also try this one: http://www.dancrintea.ro/doc-to-pdf/
Looks like this could be the issue.

Categories