23#include <PrintManagerInterop.h>
24#include <windows.ui.xaml.hosting.desktopwindowxamlsource.h>
30#include <wx/cmndata.h>
39#include <winrt/base.h>
40#include <winrt/Windows.Data.Pdf.h>
41#include <winrt/Windows.Foundation.h>
42#include <winrt/Windows.Foundation.Collections.h>
43#include <winrt/Windows.Graphics.Imaging.h>
44#include <winrt/Windows.Graphics.Printing.h>
45#include <winrt/Windows.Storage.h>
46#include <winrt/Windows.Storage.Streams.h>
47#include <winrt/Windows.UI.Xaml.h>
48#include <winrt/Windows.UI.Xaml.Controls.h>
49#include <winrt/Windows.UI.Xaml.Hosting.h>
50#include <winrt/Windows.UI.Xaml.Media.h>
51#include <winrt/Windows.UI.Xaml.Media.Imaging.h>
52#include <winrt/Windows.UI.Xaml.Printing.h>
54#include <wx/filename.h>
57namespace wdp = winrt::Windows::Data::Pdf;
58namespace wf = winrt::Windows::Foundation;
59namespace wgi = winrt::Windows::Graphics::Imaging;
60namespace wgp = winrt::Windows::Graphics::Printing;
61namespace wss = winrt::Windows::Storage::Streams;
62namespace wux = winrt::Windows::UI::Xaml;
67constexpr double PRINT_MAX_DPI = 300.0;
68constexpr double PREVIEW_MAX_DPI = 150.0;
77template <
typename FUNC>
78auto runInMta( FUNC&& aFunc )
80 return std::async( std::launch::async,
83 winrt::init_apartment( winrt::apartment_type::multi_threaded );
87 ~UNINIT() { winrt::uninit_apartment(); }
102template <
typename PRED>
103bool pumpUntil( PRED&& aDone )
110 ::MsgWaitForMultipleObjectsEx( 0,
nullptr, 50, QS_ALLINPUT, MWMO_INPUTAVAILABLE );
112 while( ::PeekMessageW( &msg,
nullptr, 0, 0, PM_REMOVE ) )
114 if( msg.message == WM_QUIT )
116 ::PostQuitMessage(
static_cast<int>( msg.wParam ) );
120 ::TranslateMessage( &msg );
121 ::DispatchMessageW( &msg );
135wss::InMemoryRandomAccessStream renderPage(
const wdp::PdfDocument& aPdf, uint32_t aIndex,
136 const wgp::PrintPageDescription& aPaper,
double aMaxDpi )
138 wdp::PdfPage page = aPdf.GetPage( aIndex );
139 wf::Size src = page.Size();
140 wf::Rect area = aPaper.ImageableRect;
141 bool rotate = ( src.Width > src.Height ) != ( area.Width > area.Height );
142 double fitW = rotate ? src.Height : src.Width;
143 double fitH = rotate ? src.Width : src.Height;
144 double scale = std::min( area.Width / fitW, area.Height / fitH );
145 double dpi = aPaper.DpiX > 0 ? std::min<double>( aPaper.DpiX, aMaxDpi ) : aMaxDpi;
146 double pxPerDip =
scale * dpi / 96.0;
148 wdp::PdfPageRenderOptions opts;
149 opts.DestinationWidth(
static_cast<uint32_t
>( std::max( 1.0, src.Width * pxPerDip ) ) );
150 opts.DestinationHeight(
static_cast<uint32_t
>( std::max( 1.0, src.Height * pxPerDip ) ) );
152 wss::InMemoryRandomAccessStream stream;
153 page.RenderToStreamAsync( stream, opts ).get();
159 wgi::BitmapDecoder decoder = wgi::BitmapDecoder::CreateAsync( stream ).get();
160 wss::InMemoryRandomAccessStream rotated;
161 wgi::BitmapEncoder encoder = wgi::BitmapEncoder::CreateForTranscodingAsync( rotated, decoder ).get();
163 encoder.BitmapTransform().Rotation( wgi::BitmapRotation::Clockwise270Degrees );
164 encoder.FlushAsync().get();
174wux::UIElement makePageElement(
const wss::InMemoryRandomAccessStream& aStream,
175 const wgp::PrintPageDescription& aPaper )
177 wux::Media::Imaging::BitmapImage bitmap;
179 bitmap.SetSource( aStream );
181 wf::Rect area = aPaper.ImageableRect;
182 wux::Controls::Image
image;
183 image.Source( bitmap );
184 image.Stretch( wux::Media::Stretch::Uniform );
185 image.Width( area.Width );
186 image.Height( area.Height );
187 image.Margin( wux::Thickness{
static_cast<double>( area.X ),
static_cast<double>( area.Y ), 0.0, 0.0 } );
188 image.HorizontalAlignment( wux::HorizontalAlignment::Left );
189 image.VerticalAlignment( wux::VerticalAlignment::Top );
191 wux::Controls::Grid root;
192 root.Children().Append(
image );
200 std::atomic<bool> done{
false };
201 std::atomic<wgp::PrintTaskCompletion> completion{ wgp::PrintTaskCompletion::Abandoned };
208 WIN_PDF_PRINTER( HWND aOwner,
const wdp::PdfDocument& aPdf,
const winrt::hstring& aJobName,
int aCurrentPage ) :
211 m_jobName( aJobName ),
212 m_pageCount( aPdf.PageCount() ),
213 m_currentPage( aCurrentPage ),
214 m_job( std::make_shared<JOB_STATE>() )
218 ~WIN_PDF_PRINTER() { cleanup(); }
225 [[maybe_unused]]
thread_local void* xamlCore =
226 winrt::detach_abi( wux::Hosting::WindowsXamlManager::InitializeForCurrentThread() );
229 m_xamlSource = wux::Hosting::DesktopWindowXamlSource();
231 m_host = ::CreateWindowExW( 0,
L"STATIC",
L"", WS_CHILD, 0, 0, 1, 1, m_owner,
nullptr,
232 ::GetModuleHandleW(
nullptr ),
nullptr );
236 wxLogTrace(
PRINTING_TRACE,
"Failed to create XAML host window" );
237 return PRINT_RESULT::FAILED_TO_PRINT;
240 winrt::check_hresult( m_xamlSource.as<IDesktopWindowXamlSourceNative>()->AttachToWindow( m_host ) );
241 m_xamlSource.Content( wux::Controls::Grid() );
243 m_printDoc = wux::Printing::PrintDocument();
244 m_docSource = m_printDoc.DocumentSource();
246 m_paginateToken = m_printDoc.Paginate(
247 [
this](
const wf::IInspectable&,
const wux::Printing::PaginateEventArgs& aArgs )
250 m_previewPaper = aArgs.PrintTaskOptions().GetPageDescription( 1 );
251 m_previewPages.clear();
252 m_printDoc.SetPreviewPageCount( m_pageCount, wux::Printing::PreviewPageCountType::Final );
255 m_previewToken = m_printDoc.GetPreviewPage(
256 [
this](
const wf::IInspectable&,
const wux::Printing::GetPreviewPageEventArgs& aArgs )
258 onPreviewPage( aArgs.PageNumber() );
261 m_addPagesToken = m_printDoc.AddPages(
262 [
this](
const wf::IInspectable&,
const wux::Printing::AddPagesEventArgs& aArgs )
264 onAddPages( aArgs.PrintTaskOptions() );
267 auto factory = winrt::get_activation_factory<wgp::PrintManager, IPrintManagerInterop>();
269 winrt::check_hresult( factory->GetForWindow( m_owner, winrt::guid_of<wgp::PrintManager>(),
270 winrt::put_abi( m_printManager ) ) );
272 std::shared_ptr<JOB_STATE> job = m_job;
273 wgp::IPrintDocumentSource
source = m_docSource;
274 winrt::hstring jobName = m_jobName;
275 bool offerCurrent = m_currentPage > 0;
277 m_taskRequestedToken = m_printManager.PrintTaskRequested(
278 [job,
source, jobName, offerCurrent](
const wgp::PrintManager&,
279 const wgp::PrintTaskRequestedEventArgs& aArgs )
281 wgp::PrintTask task = aArgs.Request().CreatePrintTask(
283 [
source](
const wgp::PrintTaskSourceRequestedArgs& aSourceArgs )
285 aSourceArgs.SetSource(
source );
288 wgp::PrintPageRangeOptions ranges = task.Options().PageRangeOptions();
289 ranges.AllowAllPages(
true );
290 ranges.AllowCurrentPage( offerCurrent );
291 ranges.AllowCustomSetOfPages(
true );
292 task.Options().DisplayedOptions().Append( wgp::StandardPrintTaskOptions::CustomPageRanges() );
295 [job](
const wgp::PrintTask&,
const wgp::PrintTaskCompletedEventArgs& aDone )
297 job->completion = aDone.Completion();
302 wf::IAsyncOperation<bool> showOp{
nullptr };
304 winrt::check_hresult( factory->ShowPrintUIForWindowAsync( m_owner, winrt::guid_of<wf::IAsyncOperation<bool>>(),
305 winrt::put_abi( showOp ) ) );
310 return showOp.Status() != wf::AsyncStatus::Started;
312 return PRINT_RESULT::CANCELLED;
314 if( showOp.Status() != wf::AsyncStatus::Completed || !showOp.GetResults() )
316 int32_t hr = showOp.Status() == wf::AsyncStatus::Error ? int32_t( showOp.ErrorCode() ) : 0;
317 wxLogTrace(
PRINTING_TRACE,
"Print UI was not shown, status %d hr 0x%08x",
int( showOp.Status() ), hr );
318 return PRINT_RESULT::FAILED_TO_PRINT;
322 m_reenableOwner = !::EnableWindow( m_owner, FALSE );
328 return job->done.load();
330 return PRINT_RESULT::CANCELLED;
332 switch( job->completion.load() )
334 case wgp::PrintTaskCompletion::Submitted:
return PRINT_RESULT::OK;
335 case wgp::PrintTaskCompletion::Failed:
return PRINT_RESULT::FAILED_TO_PRINT;
336 default:
return PRINT_RESULT::CANCELLED;
341 void onPreviewPage( int32_t aPageNumber )
343 uint32_t
index =
static_cast<uint32_t
>( aPageNumber - 1 );
347 if( m_previewPages.size() < m_pageCount )
348 m_previewPages.resize( m_pageCount,
nullptr );
350 if( !m_previewPages[
index] )
352 wss::InMemoryRandomAccessStream stream = runInMta(
355 return renderPage( m_pdf,
index, m_previewPaper, PREVIEW_MAX_DPI );
358 m_previewPages[
index] = makePageElement( stream, m_previewPaper );
361 m_printDoc.SetPreviewPage( aPageNumber, m_previewPages[
index] );
363 catch(
const winrt::hresult_error& e )
365 wxLogTrace(
PRINTING_TRACE,
"Failed to preview page %d: %s", aPageNumber, winrt::to_string( e.message() ) );
369 void onAddPages(
const wgp::PrintTaskOptions& aOptions )
373 std::vector<uint32_t> pages = selectedPages( aOptions );
374 std::vector<wgp::PrintPageDescription> papers;
376 for( uint32_t i = 0; i < pages.size(); ++i )
377 papers.push_back( aOptions.GetPageDescription( i + 1 ) );
379 std::vector<wss::InMemoryRandomAccessStream> streams = runInMta(
382 std::vector<wss::InMemoryRandomAccessStream> rendered;
384 for( uint32_t i = 0; i < pages.size(); ++i )
385 rendered.push_back( renderPage( m_pdf, pages[i], papers[i], PRINT_MAX_DPI ) );
390 for( uint32_t i = 0; i < pages.size(); ++i )
392 m_printPages.push_back( makePageElement( streams[i], papers[i] ) );
393 m_printDoc.AddPage( m_printPages.back() );
396 catch(
const winrt::hresult_error& e )
398 wxLogTrace(
PRINTING_TRACE,
"Failed to render pages for printing: %s", winrt::to_string( e.message() ) );
401 m_printDoc.AddPagesComplete();
405 std::vector<uint32_t> selectedPages(
const wgp::PrintTaskOptions& aOptions )
const
407 std::vector<uint32_t> pages;
409 for(
const wgp::PrintPageRange& range : aOptions.CustomPageRanges() )
411 wxLogTrace(
PRINTING_TRACE,
"Selected page range %d-%d", range.FirstPageNumber(), range.LastPageNumber() );
413 for( int32_t page = range.FirstPageNumber(); page <= range.LastPageNumber(); ++page )
415 if( page >= 1 &&
static_cast<uint32_t
>( page ) <= m_pageCount )
416 pages.push_back(
static_cast<uint32_t
>( page - 1 ) );
422 for( uint32_t i = 0; i < m_pageCount; ++i )
423 pages.push_back( i );
431 if( m_reenableOwner )
433 ::EnableWindow( m_owner, TRUE );
434 m_reenableOwner =
false;
438 m_printManager.PrintTaskRequested( m_taskRequestedToken );
442 m_printDoc.AddPages( m_addPagesToken );
443 m_printDoc.GetPreviewPage( m_previewToken );
444 m_printDoc.Paginate( m_paginateToken );
447 m_previewPages.clear();
448 m_printPages.clear();
449 m_printManager =
nullptr;
450 m_docSource =
nullptr;
451 m_printDoc =
nullptr;
455 m_xamlSource.Close();
456 m_xamlSource =
nullptr;
461 ::DestroyWindow( m_host );
467 wdp::PdfDocument m_pdf;
468 winrt::hstring m_jobName;
469 uint32_t m_pageCount;
471 std::shared_ptr<JOB_STATE> m_job;
473 HWND m_host =
nullptr;
474 bool m_reenableOwner =
false;
475 wux::Hosting::DesktopWindowXamlSource m_xamlSource{
nullptr };
476 wux::Printing::PrintDocument m_printDoc{
nullptr };
477 wgp::IPrintDocumentSource m_docSource{
nullptr };
478 wgp::PrintManager m_printManager{
nullptr };
479 wgp::PrintPageDescription m_previewPaper{};
480 std::vector<wux::UIElement> m_previewPages;
481 std::vector<wux::UIElement> m_printPages;
483 winrt::event_token m_taskRequestedToken{};
484 winrt::event_token m_paginateToken{};
485 winrt::event_token m_previewToken{};
486 winrt::event_token m_addPagesToken{};
497 wxFileName fn( wxString::FromUTF8( aFile ) );
498 winrt::hstring
path( fn.GetFullPath().ToStdWstring() );
500 if( !fn.FileExists() )
503 wdp::PdfDocument pdf{
nullptr };
510 auto file = winrt::Windows::Storage::StorageFile::GetFileFromPathAsync(
path ).get();
511 return wdp::PdfDocument::LoadFromFileAsync( file ).get();
514 catch(
const winrt::hresult_error& e )
516 wxLogTrace(
PRINTING_TRACE,
"Failed to load %s: %s", aFile, winrt::to_string( e.message() ) );
520 if( !pdf || pdf.PageCount() == 0 )
523 HWND owner = ::GetActiveWindow();
526 owner = ::GetForegroundWindow();
535 WIN_PDF_PRINTER printer( owner, pdf, winrt::hstring( fn.GetName().ToStdWstring() ), aCurrentPage );
538 catch(
const winrt::hresult_error& e )
540 wxLogTrace(
PRINTING_TRACE,
"Print failed: %s", winrt::to_string( e.message() ) );
542 catch(
const std::exception& e )
wxString result
Test unit parsing edge cases and error handling.