public static Graphics HRB(string PicName, PrintPageEventArgs e)
{
  //PrintPageEventArgs 圖層
  Graphics pg = e.Graphics;
  //暫存圖層
  Graphics g;

  try
  {
   //設定字體相關
   SolidBrush brush1 = new SolidBrush(Color.Black);
   Font font = new Font("新細明體", 18);
   Font font1 = new Font("新細明體", 9);
   //畫布大小
   int width = 645;//540
   int height = 455;//381
   //置入圖片至Bitmap image.
   Bitmap image = new Bitmap(PicName);
   //重新設定圖片大小
   image = new Bitmap(image, width, height);
   //將圖片加入畫布
   g = Graphics.FromImage(image);
   //載入外部URI圖形檔案
   var request0 = WebRequest.Create("URI url");
   using (var response = request0.GetResponse())
   using (var stream = response.GetResponseStream())
   {
    //透過串流將檔案取回
    Bitmap BarImage = new Bitmap(stream);
    //將圖檔繪製到畫布上面
    g.DrawImage(BarImage, int.Parse(Math.Round(width * 0.57).ToString()), int.Parse(Math.Round(width * 0.051).ToString()));
   }

   //繪製文字
   g.DrawString("006943137607", font1, brush1, int.Parse(Math.Round(width * 0.237).ToString()), int.Parse(Math.Round(height * 0.1777).ToString()));
   // 判斷目錄下檔案是否存在
   if (System.IO.File.Exists(@"button.png"))
   {
    try
    {
     //如果存在將檔案刪除
     System.IO.File.Delete(@"button.png");
    }
    catch (System.IO.IOException exx)
    {
     //若有問題將錯誤訊息繪製在畫布上回傳
     Font font2 = new Font("新細明體", 12);
     SolidBrush brushRed = new SolidBrush(Color.Red);
     pg.DrawString(exx.Message, font2, brushRed, 10, 10);
     return pg;
    }  
   }

   //儲存圖片檔為PNG
   image.Save("button.png", System.Drawing.Imaging.ImageFormat.Png);  //存到暫存
   //釋放暫存資源
   image.Dispose();
   g.Dispose();

   //讀取圖片
   Bitmap image2 = new Bitmap("button.png");
   //旋轉90度     (其他旋轉角度請看這 網址 )
   image2.RotateFlip(RotateFlipType.Rotate90FlipNone);
   //畫上至畫布
   pg.DrawImage(image2,0,0);
   //釋放資源
   image2.Dispose();
   //回傳 畫布
   return pg;
  }
  catch (System.ArgumentException ex)
  {
   Font font2 = new Font("新細明體", 12);
   SolidBrush brushRed = new SolidBrush(Color.Red);
   e.Graphics.DrawString(ex.Message, font2, brushRed, 10, 10);
   return e.Graphics;
  }
 }

結果如下圖1461650915207

順時針旋轉90度後…

1461650848759

 

Leave a Comment