0

I am developing a drawing application that should allow me to output the drawing on any paper size available on current printer. I have developed a custom preview with dedicated controls for printer settings (printer, paper size, orientation, etc). To set the paper size (paper ID) by selecting from a drop-down list I use the following code:

procedure SetPaperID(APaperID: SmallInt);
var
  Device, Driver, Port: array [0 .. 255] of Char;
  hDeviceMode: THandle;
  pDevMode: PDeviceMode;
begin
  // Set PaperID for CURRENT printer
  Printer.GetPrinter(Device, Driver, Port, hDeviceMode);
  if hDeviceMode <> 0 then
  begin
    pDevMode := GlobalLock(hDeviceMode);
    if pDevMode <> nil then
      try
        pDevMode^.dmFields := pDevMode^.dmFields or DM_PAPERSIZE;
        pDevMode^.dmPapersize := APaperID;
      finally
        GlobalUnlock(hDeviceMode);
      end;
  end;
end;

I am testing this for various paper sizes via a PDF printer (Acrobat, Nitro, Microsoft Print to PDF) and this code works fine for any APaperID that is defined in Windows.pas. For example DMPAPER_LETTER (PaperID = 1), DMPAPER_A3 (PaperID = 8), DMPAPER_A4 (PaperID = 9), etc.

However, when printing to an APaperID that is not defined in Windows.pas (e.g. ISO A0, PaperID = 142), the output is on the previously selected paper size. However, if I then open a TPrinterSetupDialog, the paper has actually changed. If I then click OK in the TPrinterSetupDialog the output is actually to the correct paper size!

What am I missing? I assumed (incorrectly?) that the GlobalUnlock flushes the DeviceMode structure (with all settings) to the printer and physically changes settings. If this is correct, why would it not work for paper sizes not defined in Windows.pas?

2
  • 2
    After changing the DeviceMode, have you tried calling Printer.SetPrinter()? Jun 3 at 22:12
  • From initial testing, this indeed solves the problem. Thanks @RemyLebeau! For good order, I now have Printer.SetPrinter before the finally (i.e. global lock still in place). Or should it be after the if then block (i.e. no lock in place)?
    – Mark
    Jun 4 at 11:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.