I need to print to an Epson TM-T70 printer (Ethernet version) with Java. I can't found documentation about this. Which is the simplest way? Maybe using JavaPOS? Is there some example?
Thanks.
for our pos, I was able to do:
/* (non-Javadoc)
* #see be.intoit.pos.epsonagent.commands.Command#execute()
*/
public void execute() throws Exception {
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
StringBuilder builder = new StringBuilder();
builder.append(toPrint);
builder.append(EscapeCodeUtil.createEscapeCode(10));
PrintRequestAttributeSet aset= new HashPrintRequestAttributeSet();
aset.add(new MediaPrintableArea(100,400,210,160,Size2DSyntax.MM));
InputStream is = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));
Doc mydoc = new SimpleDoc(is, flavor, null);
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
//print using default
DocPrintJob
job = defaultService.createPrintJob();
job.print(mydoc, aset);
}
Where The util class was:
public class EscapeCodeUtil {
public static String createEscapeCode(int ... codes)
{
StringBuilder sb = new StringBuilder();
for(int code : codes)
sb.append((char) code);
return sb.toString();
}
}
This cut the paper
Socket sock = new Socket(IP_printer, 9100);
PrintWriter oStream = new PrintWriter(sock.getOutputStream());
oStream.print(""+(char)29+(char)86+(char)0);
Related
I am trying to sign a pdf document with a signature that comes from the entire client in format base 64.
the service makes a request to calculate the hash from the document
I take the content from the pdf of the document, calculate the hash from it according to the algorithm.
service takes the received hash and signs it, sends the received signature along with the bytes of the document to be signed
I get a string in base 64 and pdf bytes to be signed
Is it possiple case? I give a code example
public byte[] insertSignature(byte[] document, String signature) {
try (InputStream inputStream = new ByteArrayInputStream(document);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ByteArrayOutputStream result = new ByteArrayOutputStream()) {
byte[] decodeSignature = Base64.decodeBase64(signature);
CAdESSignature cades = new CAdESSignature(decodeSignature, null, null);
var certificate = cades.getCAdESSignerInfo(0).getSignerCertificate();
var subject = new Subject(certificate.getSubjectX500Principal().getEncoded());
List<String> names = getSignaturesFields(document);
String sigFieldName = String.format("Signature %s", names.size() + 1);
PdfName filter = PdfName.Adobe_PPKLite;
PdfName subFilter = PdfName.ETSI_CAdES_DETACHED;
int estimatedSize = 8192;
PdfReader reader = new PdfReader(inputStream);
StampingProperties stampingProperties = new StampingProperties();
if (names.size() > 1) {
stampingProperties.useAppendMode();
}
PdfSigner signer = new PdfSigner(reader, os, stampingProperties);
signer.setCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED);
PdfSignatureAppearance appearance = signer.getSignatureAppearance();
appearance
.setContact(subject.email().orElse(""))
.setSignatureCreator(subject.organizationName().orElse(""))
.setLocation(subject.country())
.setReuseAppearance(false)
.setPageNumber(1);
signer.setFieldName(sigFieldName);
ContainerForPrepareSignedDocument external = new ContainerForPrepareSignedDocument(filter, subFilter);
signer.signExternalContainer(external, estimatedSize);
byte[] preSignedBytes = os.toByteArray();
ContainerReadyToSignedDocument extSigContainer = new ContainerReadyToSignedDocument(decodeSignature);
PdfDocument docToSign = new PdfDocument(new PdfReader(new ByteArrayInputStream(preSignedBytes)));
PdfSigner.signDeferred(docToSign, sigFieldName, result, extSigContainer);
docToSign.close();
return result.toByteArray();
}
catch (IOException e) {
throw new InternalException("IO exception by insert signature to document:", e);
}
catch (GeneralSecurityException e) {
throw new InternalException("General security by insert signature to document:", e);
}
catch (CAdESException e) {
throw new InternalException("CAdESException by insert signature to document:", e);
}
}
private List<String> getSignaturesFields(byte[] document)
throws IOException {
try (InputStream inputStream = new ByteArrayInputStream(document);
PdfReader reader = new PdfReader(inputStream);
PdfDocument pdfDocument = new PdfDocument(reader)) {
SignatureUtil signUtil = new SignatureUtil(pdfDocument);
return signUtil.getSignatureNames();
}
}
static class ContainerForPrepareSignedDocument implements IExternalSignatureContainer {
private final PdfName filter;
private final PdfName subFilter;
public ContainerForPrepareSignedDocument(PdfName filter,
PdfName subFilter) {
this.filter = filter;
this.subFilter = subFilter;
}
public byte[] sign(InputStream docBytes) {
return new byte[0];
}
public void modifySigningDictionary(PdfDictionary signDic) {
signDic.put(PdfName.Filter, filter);
signDic.put(PdfName.SubFilter, subFilter);
}
}
static class ContainerReadyToSignedDocument implements IExternalSignatureContainer {
private byte[] cmsSignatureContents;
public ContainerReadyToSignedDocument(byte[] cmsSignatureContents) {
this.cmsSignatureContents = cmsSignatureContents;
}
public byte[] sign(InputStream docBytes) {
return cmsSignatureContents;
}
public void modifySigningDictionary(PdfDictionary signDic) {
}
}
i am using a report in iReports, but I would want to print this with something changes in configuration for example: Copies, Orientation, Sides and others things; but it is not possible for me.
The fragment code is that:
InitialContext initialContext = new InitialContext();
DataSource dataSource = (DataSource) initialContext.lookup("java:/ds");
Connection connection = dataSource.getConnection();
String report = JasperCompileManager.compileReportToFile("report.jrxml");
JasperPrint jasperPrint = JasperFillManager.fillReport(report, new HashMap<String, Object>(), connection);
String defaultPrinter = PrintServiceLookup.lookupDefaultPrintService().getName().toLowerCase();
PrinterJob printerJob = PrinterJob.getPrinterJob();
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
PrintService selectedService = null;
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(Sides.DUPLEX);
for (PrintService service : services) {
String existingPrinter = service.getName().toLowerCase();
if (existingPrinter.equals(defaultPrinter)) {
selectedService = service;
break;
}
}
if (selectedService != null) {
printerJob.setPrintService(selectedService);
boolean printSucceed = JasperPrintManager.printReport(jasperPrint, false);
}
I am using java language, help me please.
I'm new in TIKA. I try to convert Microsoft word documents to HTML by using Tika. I'm using TikaOnDotNet wrapper to used TIKA on .Net framework. My conversion code is like following:
byte[] file = Files.toByteArray(new File(#"myPath\document.doc"));
AutoDetectParser tikaParser = new AutoDetectParser();
ByteArrayOutputStream output = new ByteArrayOutputStream();
SAXTransformerFactory factory = (SAXTransformerFactory)TransformerFactory.newInstance();
TransformerHandler handler = factory.newTransformerHandler();
handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html");
handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, "UTF-8");
handler.setResult(new StreamResult(output));
ExpandedTitleContentHandler handler1 = new ExpandedTitleContentHandler(handler);
tikaParser.parse(new ByteArrayInputStream(file), handler1, new Metadata());
File ofile = new File(#"C:\toHtml\text.html");
ofile.createNewFile();
DataOutputStream stream = new DataOutputStream(new FileOutputStream(ofile));
output.writeTo(stream);
everything working well except the embedded images. The generated HTML contains image tag like:
<img src="embedded:image2.wmf" alt="image2.wmf"/>
but the image source does not exists. Please advise me
Credits goes to #Gagravarr.
please note that this is a simple implementation of code, the original codes are available in comment of the questions.
This implementation is based on TikaOnDotNet wrapper.....
public class DocToHtml
{
private TikaConfig config = TikaConfig.getDefaultConfig();
public void Convert()
{
byte[] file = Files.toByteArray(new File(#"filename.doc"));
AutoDetectParser tikaParser = new AutoDetectParser();
ByteArrayOutputStream output = new ByteArrayOutputStream();
SAXTransformerFactory factory = (SAXTransformerFactory)TransformerFactory.newInstance();
var inputStream = new ByteArrayInputStream(file);
// ToHTMLContentHandler handler = new ToHTMLContentHandler();
var metaData = new Metadata();
EncodingDetector encodingDetector = new UniversalEncodingDetector();
var encode = encodingDetector.detect(inputStream, metaData) ?? new UTF_32();
TransformerHandler handler = factory.newTransformerHandler();
handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html");
handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, encode.toString());
handler.setResult(new StreamResult(output));
ContentHandler imageRewriting = new ImageRewritingContentHandler(handler);
// ExpandedTitleContentHandler handler1 = new ExpandedTitleContentHandler(handler);
ParseContext context = new ParseContext();
context.set(typeof(EmbeddedDocumentExtractor), new FileEmbeddedDocumentEtractor());
tikaParser.parse(inputStream, imageRewriting, new Metadata(), context);
byte[] array = output.toByteArray();
System.IO.File.WriteAllBytes(#"C:\toHtml\text.html", array);
}
private class ImageRewritingContentHandler : ContentHandlerDecorator
{
public ImageRewritingContentHandler(ContentHandler handler) : base(handler)
{
}
public override void startElement(string uri, string localName, string name, Attributes origAttrs)
{
if ("img".Equals(localName))
{
AttributesImpl attrs;
if (origAttrs is AttributesImpl)
attrs = (AttributesImpl)origAttrs;
else
attrs = new AttributesImpl(origAttrs);
for (int i = 0; i < attrs.getLength(); i++)
{
if ("src".Equals(attrs.getLocalName(i)))
{
String src = attrs.getValue(i);
if (src.StartsWith("embedded:"))
{
var newSrc = src.Replace("embedded:", #"images\");
attrs.setValue(i, newSrc);
}
}
}
attrs.addAttribute(null, "width", "width","width", "100px");
base.startElement(uri, localName, name, attrs);
}
else
base.startElement(uri, localName, name, origAttrs);
}
}
private class FileEmbeddedDocumentEtractor : EmbeddedDocumentExtractor
{
private int count = 0;
public bool shouldParseEmbedded(Metadata m)
{
return true;
}
public void parseEmbedded(InputStream inputStream, ContentHandler contentHandler, Metadata metadata, bool outputHtml)
{
Detector detector = new DefaultDetector();
string name = metadata.get("resourceName");
MediaType contentType = detector.detect(inputStream, metadata);
if (contentType.getType() != "image") return;
var embeddedFile = name;
File outputFile = new File(#"C:\toHtml\images", embeddedFile);
try
{
using (FileOutputStream os = new FileOutputStream(outputFile))
{
var tin = inputStream as TikaInputStream;
if (tin != null)
{
if (tin.getOpenContainer() != null && tin.getOpenContainer() is DirectoryEntry)
{
POIFSFileSystem fs = new POIFSFileSystem();
fs.writeFilesystem(os);
}
else
{
IOUtils.copy(inputStream, os);
}
}
}
}
catch (Exception ex)
{
throw;
}
}
}
}
I'm trying to print from differents printer trays using javax.print with no luck, I have a printer HP Officejet Pro X476dw with 2 paper trays numbered 1 and 2.
My code is this:
public class ImprimeSide{
public static void main (String [] args) {
try {
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(null, null);
//Acquire Printer
PrintService printer = null;
for(PrintService serv: pservices){
if(serv.getName().contains("HP Officejet")){
printer = serv;
}
}
if(printer != null){
//Open File
FileInputStream fis = new FileInputStream("Documento2.pdf");
//Create Doc out of file, autosense filetype
Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
//Create job for printer
DocPrintJob printJob = printer.createPrintJob();
//Create AttributeSet
PrintRequestAttributeSet pset = new HashPrintRequestAttributeSet();
//Add MediaTray to AttributeSet
pset.add(MediaTray.SIDE);
//Print using Doc and Attributes
printJob.print(pdfDoc, pset);
//Close File
fis.close();
}
}catch (Throwable t) {
t.printStackTrace();
}
}
}
Changing the line pset.add(MediaTray.SIDE) for every constant in the class MediaTray (TOP, BOTTOM, MANUAL.. etc) doesn't change anything, it will print taking paper from the default tray.
Any sugestion will be appreciated.
you must declare a MediaTray after mapping all media in a hashmap
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
for (PrintService service : services)
{
System.out.println(service);
// we retrieve all the supported attributes of type Media
// we can receive MediaTray, MediaSizeName, ...
Object o = service.getSupportedAttributeValues(Media.class, flavor, null);
if (o != null && o.getClass().isArray())
{
for (Media media : (Media[]) o)
{
// we collect the MediaTray available
if (media instanceof MediaTray)
{
System.out.println(media.getValue() + " : " + media + " - " + media.getClass().getName());
trayMap.put(media.getValue(), media);
}
}
}
}
MediaTray selectedTray = (MediaTray) trayMap.get(Integer.valueOf(mediaId));
and after you add it to the PrintRequestAttributeSet
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(selectedTray);
And when you print you use this PrintRequestAttributeSet
DocPrintJob job = services[0].createPrintJob();
job.print(doc, attributes);
Jorge
I am using JasperReports API to print from my Java application. I am printing a report like this:
public void prints(String billNo, String fileName, String outFileName, String perameterName) {
HashMap hm = new HashMap();
hm.put(perameterName, billNo);
//Here parameterName is the parameter in JasperReport.
// billNo is the value from my java application.
try {
conn = new connection().db();
PrinterJob job = PrinterJob.getPrinterJob();
/* Create an array of PrintServices */
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
PrintService default_service = PrintServiceLookup.lookupDefaultPrintService();
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().equals(default_service.getName().toUpperCase())) {
selectedService = i;
}
}
job.setPrintService(services[selectedService]);
PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
printRequestAttributeSet.add(MediaSizeName.ISO_A4);
printRequestAttributeSet.add(new Copies(1));
JRPrintServiceExporter exporter;
exporter = new JRPrintServiceExporter();
JasperPrint print = JasperFillManager.fillReport(fileName, hm, conn);
JRExporter exporterr = new JRPdfExporter();
exporterr.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outFileName);
exporterr.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, services[selectedService]);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, services[selectedService].getAttributes());
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, printRequestAttributeSet);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.FALSE);
exporter.exportReport();
exporterr.exportReport();
} catch (JRException e) {
JOptionPane.showMessageDialog(null, e);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Printer not connected. Check power cable.");
}
}
I use to invoke this method in other classes.
But how can I pass multiple Parameters and multiple values to report?
for example query:
"select * from table1 where date>"+thisDate+" and date<"+thatDate+" "
How can I send thisDate and thatDate from my Java application?
Since you are using a HashMap you can store there many values. You can do it like:
HashMap hm = new HashMap();
hm.put(perameterName, billNo);
hm.put("thisDate", thisDate);
hm.put("theDate", theDate);
hm.put("anotherParam", paramValue);
If you don't want your method to pass so many keys and values as arguments, you can simply pass the "hm" object to your method:
public void prints( String fileName, String outFileName, HashMap hm){