I am using Apache wicket 6.19.0, pdfbox 1.8.8, and Java 8.
The problem I am facing is I get the print dialog on screen when I deploy my application on a Windows machine, but when deployed on the Linux server it doesn't show the print dialog on screen when invoked the print functionality from UI.
Code:
public static PrintService choosePrinter() {
PrinterJob printJob = PrinterJob.getPrinterJob();
if(printJob.printDialog()) {
return printJob.getPrintService();
}else {
return null;
}
}
#Override
public File getObject() {
File file = new File("document.pdf");
file.deleteOnExit();
PDDocument document = new PDDocument();
//prepare the pdf here...
PrinterJob job = PrinterJob.getPrinterJob();
PrintService service = choosePrinter();
if(service != null){
job.setPrintService(service);
document.silentPrint(job);
}
document.close();
} catch (Exception e) {
LOGGER.error("Exception: "+e);
}
return file;
}
PrinterJob is a class from AWT, i.e. a desktop feature.
You cannot use it at the server.
Apache Wicket is a web framework so I assume your users will reach the application thru a browser. In this case you have two options:
render a good looking HTML and use JavaScript's window.print() to print it
render a PDF and stream it to the browser so that it either:
2.1. show it by using Content-Disposition: Inline response header (if the browser has PDF plugin)
2.2. ask the user to save it, by using Content-Disposition: Attachment
I am not sure whether there is a way to print the PDF with JavaScript.
Related
I have a Java method that when called, displays a shipping label pdf image in my browser. I'm using iText, as well as Apache Commons libraries for this.
import org.jasypt.contrib.org.apache.commons.codec_1_3.binary.Base64;
import com.itextpdf.text.*;
...
public void constructLabel(HttpServletResponse response) {
Document document = new Document();
byte[] image = null;
Image labelImage = null;
try {
document.setPageSize(PageSize.LETTER);
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
String base64Label = "a3B4GHHh6Y0m923xKj="; //<--This is longer, but I shortened it for this question
image = Base64.decodeBase64(base64Label.getBytes());
labelImage = Image.getInstance(image);
labelImage.setAlignment(Image.TOP);
labelImage.scalePercent(new Float("35"));
document.add(labelImage);
response.getOutputStream().write(image);
response.setContentType("application/pdf");
response.setContentLength(image.length);
document.close();
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
...
For UPS labels, it works fine. When my code runs a base-64 encoded UPS label, the label displays in the browser. But for FedEx labels, I get an error modal in the browser that says "Error Failed to load PDF document." Please see pictures of the labels (printed from an online PDF converter) and error modal below.
This has me left in the dark in that there are no errors or exceptions or stack traces in the console at all.
How can I get this code to show a PDF image of the FedEx label in the browser?
I'm developing a javafx application that opens a PDF when I pres a button. I'm using the xdg-open command in linux like this:
String[] command = {"xdg-open",path}
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
but when i pres the button nothing happens.
I tested it in a different project and it opened the PDF without problem.
Any idea how can i fix this?
Here's the method that I use. A simple call to the Desktop.getDesktop().open() method will open any given File using the system's default application.
This will also open the file in a background Thread so your application doesn't hang while waiting for the file to load.
public static void openFile(File file) throws Exception {
if (Desktop.isDesktopSupported()) {
new Thread(() -> {
try {
Desktop.getDesktop().open(file);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
This code show the document in the default browser :
File file = new File("C:/filePath/Test.pdf");
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());
I hope this help!!
I have used ICEpdf's org.icepdf.core.pobjects.Document to render the pages of my PDF's; as described here. This gives a ava.awt.image.BufferedImageper page. I convert this to a JavaFX node:
Image fxImage = SwingFXUtils.toFXImage(bufferedImage, null);
ImageView imageView = new ImageView(fxImage);
From there you can write your own simple paging viewer in JavaFX. The rendering is fast and the result looks as hoped for.
I need to send a pdf jasper directly to the printer, the current code PDF is delegated to the browser and therefore the user can print as many copies as desired. Must allow only print one copy, so I thought I'd send directly to printing.
I searched the forum but did not understand what would be the best solution to the issue.
Take a look at my code:
public class UtilRelatorios {
public static void imprimeRelatorio(String relatorioNome,
HashMap parametros) throws IOException, JRException {
FacesContext fc = FacesContext.getCurrentInstance();
ServletContext context = (ServletContext) fc.getExternalContext().getContext();
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
JasperPrint jasperPrint =
JasperFillManager.fillReport(
context.getRealPath("/relatorios")+ File.separator+relatorioNome+".jasper",
parametros);
//int finalPag = jasperPrint.getPages().size();
//System.out.println("page: "+finalPag);
//JasperPrintManager.printPage(jasperPrint,finalPag,false);
byte[] b = null;
//JasperPrintManager.printPage(jasperPrint, 0, false);
try {
b = JasperExportManager.exportReportToPdf(jasperPrint);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
if (b != null && b.length > 0) {
// Envia o relatório em formato PDF para o browser
response.setContentType("application/pdf");
int codigo = (int) (Math.random()*1000);
response.setHeader("Content-disposition","inline);filename=relatorio_"+codigo+".pdf");
response.setContentLength(b.length);
ServletOutputStream ouputStream = response.getOutputStream();
ouputStream.write(b, 0, b.length);
ouputStream.flush();
ouputStream.close();
}
}
}
If as seems in question you like to send the report directly to user's printer via web application, browser.
This can not be done!, you can not control the web users printer directly from the browser (excluding the use of activeX or other home made plugins)
Probably this is luck since otherwise while navigating on internet you would have people printing alot of advertising on your printer....
If instead you like to send it to a printer attached to server, this can be done!
If its the server printer please let me know and I can pass you some code.
If the client & server PC are on the same network ie LAN, you can share the client's printer on the server, then send report to it just like you'd send to a locally installed printer.
I need a Java program that prints any file to the default/selected printer (actually I am using RICOH universal PostScript printer that prints any file to a PostScript file). Furthermore I will read that stream from the printer and write it to a PostScript file. I already tried below sample program from google, but when I am getting the PostScript file it is in some unknown format.
public class PrintToFileWithJava {
private static boolean jobRunning = true;
public static void main(String[] args) throws Exception {
InputStream is = new BufferedInputStream(new FileInputStream("Authentication in Hive.pdf"));
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob printJob = service.createPrintJob();
printJob.addPrintJobListener(new JobCompleteMonitor());
Doc doc = new SimpleDoc(is, flavor, null);
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
printJob.print(doc, attributes);
while (jobRunning) {
Thread.sleep(1000);
}
System.out.println("Exiting app");
is.close();
}
private static class JobCompleteMonitor extends PrintJobAdapter {
#Override
public void printJobCompleted(PrintJobEvent jobEvent) {
System.out.println("Job completed");
jobRunning = false;
}
}
}
Any suggestions are appreciated.
What you want to do is possible in Java but it's not simple. You'll have to write a framework which can read all the file types that you want to support and which can render those files using the Java Graphics2D API.
That is a lot of work. You can make your life easier by using an existing framework like ImageMagick which can convert a lot of image formats to PostScript.
For printing Word and other proprietary formats, you need special converters. If the application is installed, you can try Desktop.print(). If not, then you'll have to find a library which can render these documents for you.
I have a java application to print and auto cut the receipt using a thermal printer (Bixolon srp 350 plus)
Initially I was having problem with auto cutting the receipt but after many trials and google search, I somehow manage to auto cut the receipt. But the problem is that when I deploy the war application in my test machine, it prints fine but it is not cutting the paper at the end. I even deployed the war file into my development machine's tomcat and it is auto cutting fine.
Both the development machine and the test machine are using windows 7 - ultimate , the same apache-tomcat-6.0.18 , and JDK6/JRE6 .
Initially the Test machine had jre6 installed and after auto cutting was unsuccessful . I installed jdk6 which i was using in my development machine to no success.
The two machines are of different brands with different hardware configuration.
Can anyone please help me out on this? Is this something to do with the previous JRE6 installed and was not properly removed from windows registry?
I am using grails 1.3.7 along with mysql 5.5.
My code is below :
public void printBill(String printData) throws Exception {
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(5));
pras.add(new PrinterResolution(180,180,PrinterResolution.DPI));
PrintService pss[] = PrintServiceLookup.lookupPrintServices(null,pras);
if (pss.length == 0) {
throw new RuntimeException("No printer services available.");
}
if(printData == null) {
throw new Exception("nothing to print");
}
PrintService ps = pss[0];
DocPrintJob job = ps.createPrintJob();
DocAttributeSet das = new HashDocAttributeSet();
das.add(new PrinterResolution(180,180,PrinterResolution.DPI));
byte[] desc = printData.getBytes();
Doc doc = new SimpleDoc(desc, DocFlavor.BYTE_ARRAY.AUTOSENSE, das);
try {
job.print(doc, pras);
cutPaper();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* TODO improvision to auto cut bill, need to find a proper way to cut
*/
private void cutPaper() throws Exception{
TempPageCutter pageCutter = new RestaurantPrinter().new TempPageCutter();
pageCutter.cutReceipt();
}
private class TempPageCutter implements Printable {
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
if(pageIndex > 0)
return NO_SUCH_PAGE;
System.out.println("Cutting");
graphics.drawString("", 0, 0);
return PAGE_EXISTS;
}
public void cutReceipt() throws PrinterException {
System.out.println("cutReceipt");
PrintService[] printService = PrinterJob.lookupPrintServices();
if(printService == null || printService.length < 1) {
return;
}
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
job.print();
}
}
If anyone can help me out with a better way to implement the auto cutting functionality it would be a great help.
I was able to resolve the auto cutting issue by setting the bixolon srp 350 plus printer as the default printer in the windows 7 printer setting page. Still its a bit weird. If anyone can help me with a better way to implement auto cutting functionality , it will still be a great help. Cheers!