2017-06-09 39 views
1

在從PDFPrintTest樣本中進行測試時,我們注意到示例2與事件處理程序的示例1相結合的行爲不正確。Pdfnet打印樣本不工作

例PrintPage事件處理程序的1:

void PrintPage(object sender, PrintPageEventArgs ev) 
    { 
     Graphics gr = ev.Graphics; 
     gr.PageUnit = GraphicsUnit.Inch; 

     Rectangle rectPage = ev.PageBounds;   //print without margins 
     //Rectangle rectPage = ev.MarginBounds;  //print using margins 

     float dpi = gr.DpiX; 
     if (dpi > 300) dpi = 300; 

     int example = 1; 
     bool use_hard_margins = false; 

     // Example 1) Print the Bitmap. 
     if (example == 1) 
     { 
      pdfdraw.SetDPI(dpi); 
      Bitmap bmp = pdfdraw.GetBitmap(pageitr.Current()); 
      //bmp.Save("tiger.jpg"); 

      gr.DrawImage(bmp, rectPage, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel); 
     } 

全樣本代碼在這裏:https://www.pdftron.com/pdfnet/samplecode/PDFPrintTest.cs.html

你會注意到在評論中bmp.Save("tiger.jpg");,這就是它出錯的地步。如果我們運行代碼並保存bmp,我們就可以得到我們需要的jpg文件。然而,gr.DrawImage(bmp, rectPage, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);打印一個普通的空白PDF頁面。這是爲什麼 ?

我們的目標:在某些情況下,我們需要強制使用40%灰度的打印作業。 Winforms不支持這一點,我們只能設置灰度,沒有指定百分比,所以我們希望截取打印並將輸出更改爲40%的灰度,這導致我們轉到了PdfNet Print樣本。從這些示例中,處理程序中只有示例2具有Graphics gr,它接受用於設置所需頁面中灰度級的顏色矩陣。

任何非PdfNet解決方案都是受歡迎的,但樣例代碼不能正常工作仍然很奇怪。

回答

1

我們得到它的工作,顯然它只是在打印到PDF時纔給出一個白頁。完全相同的代碼呈現太小的圖像,但實際上打印。 我們仍然不完全確定問題所在,但是制定了可以正確打印到pdf的新代碼,並將全尺寸打印到打印機。

void PrintPage(object sender, PrintPageEventArgs ev) 
    { 
     Graphics gr = ev.Graphics; 
     gr.PageUnit = GraphicsUnit.Pixel; //this has been changed to Pixel, from Inch. 

     float dpi = gr.DpiX; 
     //if (dpi > 300) dpi = 300; 


     Rectangle rectPage = ev.PageBounds;   //print without margins 
     //Rectangle rectPage = ev.MarginBounds;  //print using margins 

     float dpi = gr.DpiX; 


     int example = 1; 
     bool use_hard_margins = false; 

     // Example 1) Print the Bitmap. 
     if (example == 1) 
     { 
      pdfdraw.SetDPI(dpi); 
      pdfdraw.SetDrawAnnotations(false); 
      Bitmap bmp = pdfdraw.GetBitmap(pageitr.Current()); 



      gr.DrawImage(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel); 
     } 

` 

if (dpi > 300) dpi = 300;這是在渲染過小圖像的罪魁禍首被髮送到打印機。它還解決了「白色pdf」問題。 其次,我們沒有將rectPage傳遞給DrawImage,並將其替換爲:new Rectangle(0, 0, bmp.Width, bmp.Height)

我可以理解發送到打印機的較小尺寸,但爲什麼它沒有選擇打印到PDF的任何內容仍不清楚。

儘管最終目標仍然是打印,但使用正確的「打印到pdf」進行調試和測試要容易得多。上面的代碼在2個獨立的項目中起作用,所以我會假設這確實解決了這個問題。

+0

太好了,謝謝。我們將審查和更新我們的示例代碼。 – Ryan

1

謝謝你指出這一點。就像你一樣,我不清楚爲什麼bmp.Save工作正常,但Graphics.DrawImage(bmp,...只顯示背景顏色。我懷疑它與其他參數傳遞到Graphics.DrawImage

由於該位圖對象是正確的,那麼這個特定的問題是一個真正的.Net問題,而不是一個PDFNet問題,我目前無法回答。

樣本的其他部分運行正常,使用PDFDraw.DrawInRect。這不適合你嗎?

+0

我們現在成功打印頁面,奇怪的是,它並沒有'打印到pdf'。儘管如此,爲了測試目的而實際打印卻有點麻煩。 我們現在有我們需要的東西,但它爲什麼只顯示'print to pdf'中的白頁仍然是一個謎。事實上,這可能是一個.NET問題。 –

+0

瑞恩,我添加了一個代碼片段,爲我們工作,作爲答案。希望你能從中得到一些東西,以防你想改變你的示例代碼。 –

+0

如果您有新的或單獨的問題,請發佈新的SO問題。 – Ryan