I would like to print multiple pdfs from java (using the java print service) in a single print job.
I would like to send multiple pdfs as a single job to the printer. This is so that all the documents in my 'batch' print together and are not interleaved with someone else's print jobs when I go pick them up from the printer.
A batch potentially consists of 1000s of print jobs.
I tried jpedal, but it does not support java.awt.print.Book
Book book = new Book();
PdfDecoder pdfDecoder = readFileApplyOptions("C:/Temp/singlepagetest.pdf", pageFormat);
book.append(pdfDecoder, pageFormat);
PdfDecoder pdfDecoderTwo = readFileApplyOptions("C:/Temp/printfax-test.pdf",pageFormat);
book.append(pdfDecoderTwo, pageFormat);
printJob.setPageable(book);
printJob.print();
only prints out the first pdf. How do I print multiple pdfs in a single job?
readFileAndApplyOptions() basically creates a new PdfDecoder object and returns it.
I also tried Sun's PDFRenderer PDFRenderer in a similar fashion (using the Book object), but my code still only prints out the first page only.
Has anyone encountered a similar issue before? Is there a solution I might be missing?
Not Java specific, but I've experience of this one in C#. I solved it by printing each document to a file (programmatically equivalent to checking the "PrintToFile" checkbox on a print dialog), then concatenated each file into a memory stream, which I passed to the Win32 API printer spool in raw format (since the output to file was already correctly formatted by default).
You might be able to use a similar technique in Java
I met the same difficulties when printing at once several JPanels of a JTabbedPane, each on a separate page. I gather them in a Book but it only prints the first page.
The Book class works well (right number of pages), but I suppose the problem comes from setPageable. Since a Book is not a Printable, I made it, and it works !
Workaround:
Design a PrintableBook class : extends Book, implements Printable
public class PrintableBook extends Book implements Printable {
Vector<Printable> pages;// NB: we assume pages are single
public PrintableBook() {
super();
pages = new Vector<Printable>();
}
public void add(Printable pp) {
append(pp, pp.getPageFormat());
pages.add(pp);
}
public int print(Graphics g, PageFormat pf, int pageIndex) {
if (pageIndex >= pages.size())
return NO_SUCH_PAGE;
else {
Printable pp = pages.elementAt(pageIndex);
return pp.print(g, pf, 0);
}
}
}
Then use printJob.setPrintable( printableBook ) instead of setPageable
You should merge all of your pdf documents in one document using iText library and then print the merged document page by page.
see Print a PDF Document in Java
AFAIK, you can't, multiple documents will be printed in multiple jobs.
A workaround could be join all the pdf into a single document and print them.
:-/
Related
I am working with OleAutomation Java APIs provided by SWT(Standard Widget Toolkit) to manipulate Visio documents. We have generated Java wrappers over automation APIs using OleAutomation calls. for e.g :(shape delete)
/**
* COM Id: 11
*/
public void Delete() {
//Invoke
Variant varInputArray[] = new Variant[0];
Variant varResult = oleAutomation.invoke(11, varInputArray);
for (Variant _varItr : varInputArray) {
_varItr.dispose();
}
if(varResult !=null)
{
varResult.dispose();
}
}
I am facing a peculiar problem when calling this delete from a certain place in the application logic. On a page I place a shape and call delete. For odd numbered calls the delete is successful and the varResult returns VT_EMPTY(1st,3rd,5th.... time call). For even numbered calls (I place the shape again on the page and call -2nd,4th 6th etc) the varResult returns "null" which indicates failure. Now I need to understand what's going wrong with even numbered call. Is there some kind of logging facility in Visio Automation framework which can log the reason for failure ?
Try deleting shapes backwards. I.e. iterate collection backwards when deleting shapes.
That means, instead of:
shapes = Page.Shapes;
foreach (shape : shapes)
{
if (xxx)
shape.Delete()
}
Try this
shapes = Page.Shapes;
for (int i = shapes.Count; i > 0; --i)
{
if (xxx)
shapes[i].Delete()
}
Means, Visio has a bit "naive" collection management, so deleting items from collection while iterating over it may put you in troubles, and should be done carefully, like one would do for an array.
Alternatively, you can first select all shapes to delete and then delete them in one shot:
shapes = Page.shapes;
sel = Page.CreateSelection(visSelTypeEmpty);
foreach (shape : shapes)
{
if (xxx)
sel.Select(shape, visSelect);
}
sel.Delete();
I've started looking at XLLoop as I need a way of getting data from a java system into Excel (2010 version).
I've followed the java SimpleServer example on the front page of the website:
package org.boris.xlloop.util;
import org.boris.xlloop.FunctionServer;
import org.boris.xlloop.handler.*;
import org.boris.xlloop.reflect.*;
public class ServerExample
{
public static void main(String[] args) throws Exception {
// Create function server on the default port
FunctionServer fs = new FunctionServer();
// Create a reflection function handler and add the Math methods
ReflectFunctionHandler rfh = new ReflectFunctionHandler();
rfh.addMethods("Math.", Math.class);
rfh.addMethods("Math.", Maths.class);
rfh.addMethods("CSV.", CSV.class);
rfh.addMethods("Reflect.", Reflect.class);
// Create a function information handler to register our functions
FunctionInformationHandler firh = new FunctionInformationHandler();
firh.add(rfh.getFunctions());
// Set the handlers
CompositeFunctionHandler cfh = new CompositeFunctionHandler();
cfh.add(rfh);
cfh.add(firh);
fs.setFunctionHandler(new DebugFunctionHandler(cfh));
// Run the engine
System.out.println("Listening on port " + fs.getPort() + "...");
fs.run();
}
}
and have successfully been able to integrate simple static java methods into Excel that return one value. E.g.Math.random(), Math.pow(2, 4.45) which both return a single double.
However, I have been unable to integrate any functions that return an array/list of values. For example, in the above we have registered the Maths class (an XLLoop class) for use in Excel. This class contains a static method
public static double[] normalDist(int var0)
The method returns an array of length var0, however when I call this in Excel only one cell is populated with a value, I would have expected var0 cells to have been populated. This seems like a fairly fundamental feature to me, so I'm pretty sure I must be doing something daft.
If there is anyone out there who could help with this it would be greatly appreciated.
I should also mention that I found a similar SO question , linked from a R related SO questions feed. Unfortunately the original SO question has been removed from SO by the poster...
You need to enter the function calling the method that returns an array as a matrix-function in excel: select the cells that shall recieve the returned data, enter the function and hit ctrl-shift-enter.
If the range selected is too small, then only the values fitting in the range are displayed.
I am implementing REST through RESTlet. This is an amazing framework to build such a restful web service; it is easy to learn, its syntax is compact. However, usually, I found that when somebody/someprogram want to access some resource, it takes time to print/output the XML, I use JaxbRepresentation. Let's see my code:
#Override
#Get
public Representation toXml() throws IOException {
if (this.requireAuthentication) {
if (!this.app.authenticate(getRequest(), getResponse()))
{
return new EmptyRepresentation();
}
}
//check if the representation already tried to be requested before
//and therefore the data has been in cache
Object dataInCache = this.app.getCachedData().get(getURI);
if (dataInCache != null) {
System.out.println("Representing from Cache");
//this is warning. unless we can check that dataInCache is of type T, we can
//get rid of this warning
this.dataToBeRepresented = (T)dataInCache;
} else {
System.out.println("NOT IN CACHE");
this.dataToBeRepresented = whenDataIsNotInCache();
//automatically add data to cache
this.app.getCachedData().put(getURI, this.dataToBeRepresented, cached_duration);
}
//now represent it (if not previously execute the EmptyRepresentation)
JaxbRepresentation<T> jaxb = new JaxbRepresentation<T>(dataToBeRepresented);
jaxb.setFormattedOutput(true);
return jaxb;
}
AS you can see, and you might asked me; yes I am implementing Cache through Kitty-Cache. So, if some XML that is expensive to produce, and really looks like will never change for 7 decades, then I will use cache... I also use it for likely static data. Maximum time limit for a cache is an hour to remain in memory.
Even when I cache the output, sometimes, output are irresponsive, like hang, printed partially, and takes time before it prints the remaining document. The XML document is accessible through browser and also program, it used GET.
What are actually the problem? I humbly would like to know also the answer from RESTlet developer, if possible. Thanks
I am trying to get the values of from the following xml, but the code i've written returns a bunch of question-marks instead of what it was supposed to return. I'm guessing it must be some encoding issue, but I haven't found anything about that yet on the web.
<channel>
<title>ΖΩΔΙΑ Προβλέψεις, 1 Σεπτεμβρίου 2012</title>
</channel>
zodiaClass.java
public class zodiaClass {
#Root(strict = false)
public static class Example {
#Path("channel")
#Element
private String title;
}
public static void main(String[] list) throws Exception {
Persister persister = new Persister();
File file = new File("example1/download.xml");
Example example = persister.read(Example.class, file);
System.out.println(example.title);
}
}
output:
????? ??????????, 1 ??????????? 2012
[As requested, this is a translation of the above comment thread into the form of an answer.]
I suspect that the issue is with the output, rather than with the input. Not all command-line environments support Greek. To test this, you can try System.out.println("\u03B1"); if your command-line supports Greek, it should show up as α (lowercase alpha).
In one of your comments, you mention that you're using Eclipse. If it does turn out that the problem is with the output, then a Google search for Eclipse console encoding suggests that there are a number of different approaches that people have tried successfully — everything from modifying the relevant Run Configuration within Eclipse to editing eclipse.ini and the system encoding.
Update: [not really an update, but I'm trying to maintain the illusion of a regular answer . . .] I see from your follow-up comment that you were able to change the console encoding by changing the encoding of the *.java file. Cool!
My cell phone provider offers a limited number of free text messages on their website. I frequently use the service although I hate constantly having a tab open in my browser.
Does anyone know/point me in the right direction of how I could create a jar file/command line utility so I can fill out the appropriate forms on the site. I've always wanted to code up a project like this in Java, just in case anyone asks why I'm not using something else.
Kind Regards,
Lar
Try with Webdriver from Google or Selenium.
Sounds like you need a framework designed for doing functional testing. These act as browsers and can navigate web sites for testing and automation. You don't need the testing functionality, but it would still serve your needs.
Try HtmlUnit, or LiFT, which is a higher-level abstraction built on HtmlUnit.
Use Watij with the Eclipse IDE. When your done, compile as an .exe or run with a batch file.
Here is some sample code I wrote for filling in fields for a Google search, which can be adjusted for the web form you want to control :
package goog;
import junit.framework.TestCase;
import watij.runtime.ie.IE;
import static watij.finders.SymbolFactory.*;
public class GTestCases extends TestCase {
private static watij.runtime.ie.IE activeIE_m;
public static IE attachToIE(String url) throws Exception {
if (activeIE_m==null)
{
activeIE_m = new IE();
activeIE_m.start(url);
} else {
activeIE_m.goTo(url);
}
activeIE_m.bringToFront();
return (activeIE_m);
}
public static String getActiveUrl () throws Exception {
String currUrl = activeIE_m.url().toString();
return currUrl;
}
public void testGoogleLogin() throws Exception {
IE ie = attachToIE("http://google.com");
if ( ie.containsText("/Sign in/") ) {
ie.div(id,"guser").link(0).click();
if ( ie.containsText("Sign in with your") ||
ie.containsText("Sign in to iGoogle with your")) {
ie.textField(name,"Email").set("test#gmail.com");
ie.textField(name,"Passwd").set("test");
if ( ie.checkbox(name,"PersistentCookie").checked() ){
ie.checkbox(name,"PersistentCookie").click();
}
ie.button(name,"signIn").click();
}
}
System.out.println("Login finished.");
}
public void testGoogleSearch() throws Exception {
//IE ie = attachToIE( getActiveUrl() );
IE ie = attachToIE( "http://www.google.com/advanced_search?hl=en" );
ie.div(id,"opt-handle").click();
ie.textField(name,"as_q").set("Watij");
ie.selectList(name,"lr").select("English");
ie.button(value,"Advanced Search").click();
System.out.println("Search finished.");
}
public void testGoogleResult() throws Exception {
IE ie = attachToIE( getActiveUrl() );
ie.link(href,"http://groups.google.com/group/watij").click();
System.out.println("Followed link.");
}
}
It depends on how they are sending the form information.
If they are using a simple GET request, all you need to do is fill in the appropriate url parameters.
Otherwise you will need to post the form information to the target page.
You could use Watij, which provides a Java/COM interface onto Internet Explorer. Then write a small amount of Java code to navigate the form, insert values and submit.
Alternatively, if it's simple, then check out HttpClient, which is a simple Java HTTP client API.
Whatever you do, watch out that you don't contravene your terms of service (easy during testing - perhaps you should work against a mock interface initially?)
WebTest is yet another webapp testing framework that may be easier to use than the alternatives cited by others.
Check out the Apache Commons Net Package. There you can send a POSt request to a page. This is quite low level but may do what you want (if not you might check out the functional testing suites but it is probably not as easy to dig into).
As jjnguy says, you'll need to dissect the form to find out all the parameters.
With them you can form your own request using Apache's HTTP Client and fire it off.