-
-
Save tresf/f5fc8cc19037fece6230461bda7c13ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import com.sun.jna.Memory; | |
import com.sun.jna.Native; | |
import com.sun.jna.platform.win32.WinDef; | |
import com.sun.jna.platform.win32.WinNT; | |
import com.sun.jna.platform.win32.Winspool; | |
import javax.print.PrintServiceLookup; | |
/** | |
* Winspool2.java: | |
* | |
* long DocumentProperties(WinDef.HWND hWnd, HANDLE hPrinter, String pDeviceName, Pointer pDevModeOutput, Pointer pDevModeInput, DWORD fMode); | |
*/ | |
public class DevModeTest { | |
public static void main(String ... args) { | |
// Get a printer name from Java to use | |
//String printer = PrintServiceLookup.lookupDefaultPrintService().getName(); | |
String printer = "Microsoft Print to PDF"; | |
// Get custom Winspool2 instance | |
Winspool2 winspool = Winspool2.INSTANCE; | |
// Get printer handle from Winspool | |
WinNT.HANDLEByReference hPrinter = new WinNT.HANDLEByReference(); | |
boolean success = winspool.OpenPrinter(printer, hPrinter, null); | |
System.out.println("OpenPrinter status: " + success); | |
if(getLastError() || !success) { | |
System.err.println("Can't open printer, stopping"); | |
return; | |
} | |
// Get DEVMODE size | |
WinDef.DWORD fMode = new WinDef.DWORD(0); // 0 = size of DEVMODE structure | |
long bufferSize = winspool.DocumentProperties(null, hPrinter.getValue(), printer, null, null, fMode); | |
if(getLastError() || bufferSize == 0) { | |
System.err.println("Problem calling DocumentProperties"); | |
} else { | |
System.out.println("The DEVMODE size must be " + bufferSize); | |
fMode = new WinDef.DWORD(2); // 2 = DM_OUT_BUFFER | |
Memory devmodeBuffer = new Memory(bufferSize); | |
long status = winspool.DocumentProperties(null, hPrinter.getValue(), printer, devmodeBuffer, null, fMode); | |
// TODO: This may throw false error | |
long IDOK = 1; | |
if (getLastError()) { | |
System.err.println("Problem calling DocumentProperties"); | |
} | |
if(status == IDOK) { | |
System.out.println("The call to DocumentProperties returned IDOK"); | |
} else { | |
// API states a negative value is equivalent to an error | |
System.err.println("The call to DocumentProperties returned " + status); | |
} | |
} | |
// Close printer handle | |
winspool.INSTANCE.ClosePrinter(hPrinter.getValue()); | |
} | |
private static boolean getLastError() { | |
int error = Native.getLastError(); | |
if(error == 0) { | |
System.out.println(" OK"); | |
return false; | |
} else { | |
System.out.println(" ERROR: " + error); | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment