UWInfo Blog
發表新文章
[Join] | [忘記密碼] | [Login]
搜尋

搜尋意見
文章分類-#Author#
[所有文章分類]
所有文章分類
  • ASP.NET (48)
  • ASP.NET2.0 (15)
  • ASP.NET4.0 (34)
  • JavaScript (49)
  • jQuery (26)
  • FireFox (4)
  • UW系統設定 (3)
  • SQL (39)
  • SQL 2008 (25)
  • mirror (4)
  • SVN (4)
  • IE (9)
  • IIS (20)
  • IIS6 (1)
  • 閒聊 (7)
  • W3C (6)
  • 作業系統 (9)
  • C# (24)
  • CSS (12)
  • FileServer (1)
  • HTML 5 (11)
  • CKEditor (3)
  • UW.dll (13)
  • Visual Studio (16)
  • Browser (8)
  • SEO (1)
  • Google Apps (3)
  • 網站輔助系統 (4)
  • DNS (5)
  • SMTP (4)
  • 網管 (11)
  • 社群API (3)
  • SSL (4)
  • App_Inventor (1)
  • URLRewrite (2)
  • 開發工具 (6)
  • JSON (1)
  • Excel2007 (1)
  • 試題 (3)
  • LINQ (1)
  • bootstrap (0)
  • Vue (3)
  • IIS7 (3)
  • foodpanda (2)
  • 編碼 (2)
  • 資安 (3)
  • Sourcetree (1)
  • MAUI (1)
  • CMD (1)
  • my sql (1)
最新回應
  • Newtonsoft.Json.JsonConvert.DeserializeObject 失敗的情況
    test...more
  • dotnet ef dbcontext scaffold
    ...more
  • [ASP.NET] 利用 aspnet_regiis 加密 web.config
    ...more
  • IIS ARR (reverse proxy) 服務安裝
    ...more
  • [錯誤訊息] 請加入 ScriptResourceMapping 命名的 jquery (區分大小寫)
    ...more
  • 用 Javascript 跨網頁讀取 cookie (Cookie cross page, path of cookie)
    ...more
  • 線上客服 - MSN
    本人信箱被盜用以致資料外洩,是否可以請貴平台予以協助刪除該信箱之使用謝謝囉...more
  • 插入文字到游標或選取處
    aaaaa...more
  • IIS 配合 AD (Active Directory) 認証, 使用 .Net 6.0
    太感謝你了~~~你救了我被windows 認證卡了好幾天QQ...more
  • PostgreSQL 的 monitor trigger
    FOR EACH ROW 可能要改為 FOR EACH STATEMENT ...more
標籤
  • ef
  • MS8qKi9XQU
  • win
  • 試,
  • 9347
  • z-index
  • 許蓋功
  • Message
  • json
  • [t]
  • date order
  • SSL
  • -5959 UNIO
  • 具有潛在危險 Req
  • 20
  • ad
  • VS
  • @@S2efe
  • orm
  • query
  • 1124
  • 使用者
  • uw
  • 3662
  • Line
  • 202
  • JsonConver
  • ti
  • google搜尋
  • 檔案分享
  • O93Lp61v
  • 0
  • FB
  • 參數超過1,000
  • 還原
  • c
  • 12
  • CCE-44186-
  • firefox
  • 內碼
  • DB.OrderMa
  • 230
  • unt
  • print
  • linepay
  • 貼
  • -2484 UNIO
  • ses
  • IP
  • -6666
頁數 11 / 27 上一頁 下一頁
搜尋 ef 結果:
幫輸出的 Excel 加上表頭 (NPOI, UW.ExcelPOI.DTToExcelAndWriteToClient)
我想大家一定會遇到要把資料匯出成 Excel 的需求. 以現有的工具, 大家想到作法大概都是先把資料放到一個 datatable 之中, 後叫用 UW.ExcelPOI.DTToExcelAndWriteToClient 就結束了.

前兩天遇到一個需求, 輸出的 Excel 要加上表頭, 如下圖



於是乎把  UW.ExcelPOI.DTToExcelAndWriteToClient 做了一些擴充, (其實應該說是幫 DTToWorkSheet 做了擴充), 過程如下.

1. 需求: 一個可以快速填入欄位的 Sub (method or function)
A. 每一個 Cell 可以設定內容(文字), 字型大小, 跨欄數, 對齊方式. (其它的未來再來擴充, 例如顔色).
B. 每一個 Row 由 Cell 組成, 由左到右.
C. 一次可以填多個 Row

2. 實作:
A. 先定義 Cell
    Public Class Cell
        Public Content As String
        Public Colspan As Int32 = 1
        Public Alignment As NPOI.SS.UserModel.HorizontalAlignment
        Public FontHeightInPoints As Int32 = 0

        Sub New(Content As String, Optional Colspan As Int32 = 1,
                Optional Alignment As NPOI.SS.UserModel.HorizontalAlignment = NPOI.SS.UserModel.HorizontalAlignment.General,
                Optional FontHeightInPoints As Int32 = 0)
            Me.Content = Content
            Me.Colspan = Colspan
            Me.Alignment = Alignment
            Me.FontHeightInPoints = FontHeightInPoints
        End Sub
    End Class


B. Row 的格式: 我想最直的覺的就是 List(of Cell) 了吧.

C. 多個 Row 的表示法: List(Of List(Of Cell))

D. 來把 Cell 填入 WorkSheet  吧, 
Public Shared Sub AddRows(WS As HSSFSheet, ltRows As List(Of List(Of Cell)), ByRef StartRow As Int32)

共有三個參數: WS  和 ltRows 應該不用解釋了. 最後一個 StartRow 用來指定插入資料的開始 Row.

E.  完整程式碼: (程式碼不看沒關係, 但要跳到 F. 重點講解哦)
Public Shared Sub AddRows(WS As HSSFSheet, ltRows As List(Of List(Of Cell)), ByRef StartRow As Int32)
        Dim WR As HSSFRow
        If ltRows IsNot Nothing Then
            For Each ltRow As List(Of Cell) In ltRows
                WR = WS.CreateRow(StartRow)
                Dim C As Int32 = 0
                For Each cell As Cell In ltRow
                    Dim ic As NPOI.SS.UserModel.ICell = WR.CreateCell(C)
                    ic.SetCellValue(cell.Content)

                    Dim cs As NPOI.SS.UserModel.ICellStyle = WS.Workbook.CreateCellStyle()
                    cs.Alignment = cell.Alignment
                    If cell.FontHeightInPoints > 0 Then
                        Dim oFont As NPOI.SS.UserModel.IFont = WS.Workbook.CreateFont()
                        oFont.FontHeightInPoints = cell.FontHeightInPoints
                        cs.SetFont(oFont)
                    End If

                    ic.CellStyle = cs

                    If cell.Colspan > 1 Then
                        WS.AddMergedRegion(New CellRangeAddress(StartRow, StartRow, C, C + cell.Colspan - 1))
                        C += cell.Colspan - 1
                    End If
                    C += 1
                Next

                StartRow += 1
            Next
        End If
    End Sub


F. 重點講解:
這個 function 在實作時有兩個卡點:
1. 如何合併欄: 
WS.AddMergedRegion(New CellRangeAddress(StartRow, StartRow, C, C + cell.Colspan - 1))

2. 如何設定字型大小和對齊方式:
                    Dim cs As NPOI.SS.UserModel.ICellStyle = WS.Workbook.CreateCellStyle()
                    cs.Alignment = cell.Alignment
                    If cell.FontHeightInPoints > 0 Then
                        Dim oFont As NPOI.SS.UserModel.IFont = WS.Workbook.CreateFont()
                        oFont.FontHeightInPoints = cell.FontHeightInPoints
                        cs.SetFont(oFont)
                    End If

                    ic.CellStyle = cs


這裡有件有有趣的事, 我一開始是這樣寫的.
ic.CellStyle.Alignment = cell.Alignment

結果是整個 WorkSheet 的對齊方式都被改了. 我猜當 WorkSheet 初建立時, CellStyle 都是用同一個. 所以改任一個 cell 的 CellStyle 會同時改到所有 cell 的.

G. 使用方式:
        Dim ltHeader As New List(Of List(Of UW.ExcelPOI.Cell))
        Dim ltLine As New List(Of UW.ExcelPOI.Cell)
        ltLine.Add(New UW.ExcelPOI.Cell(DB.SysConfig.SYSTEM_NAME & "應收明細表", 16,
                                        NPOI.SS.UserModel.HorizontalAlignment.Center, 28))
        ltHeader.Add(ltLine)

        '第二行
        ltLine = New List(Of UW.ExcelPOI.Cell)
        ltLine.Add(New UW.ExcelPOI.Cell("期間: " & Me.txtbl_date_s.Text & " ~ " & Me.txtbl_date_e.Text, 10,
                                        NPOI.SS.UserModel.HorizontalAlignment.Left, 20))
        ltLine.Add(New UW.ExcelPOI.Cell("製表日期: " & Now.ToString("yyyy-MM-dd"), 6,
                                        NPOI.SS.UserModel.HorizontalAlignment.Right, 20))
        ltHeader.Add(ltLine)

        UW.ExcelPOI.DTToExcelAndWriteToClient(newdt, ltHeader:=ltHeader)
More...
Bike, 2017/6/4 下午 07:19:27
網站同時使用 C# 與 VB.net
由於早期網站都是VB.net寫的,若是直接換成 C#,就會耗費很多時間在轉換程式上
因此 ASP.NET 特別可以在同一網站同時寫 vb 跟 C#,方式是在 web.config compilation 加上設定
    <compilation debug="true" defaultLanguage="c#" targetFramework="4.0">
     <codeSubDirectories>
        <add directoryName="VB_Code"/>
        <add directoryName="CS_Code"/>
     </codeSubDirectories>
    </compilation>

也就是 VB.NET 的 code 就放到 ~\APP_Code\VB_Code 目錄
C# 的 code 就放到 ~\APP_Code\CS_Code 目錄
這樣做有兩點要注意
1.  Namespace 的命名,最好不要互相衝突, 要能夠區分出來
2.  VB_Code 與 CS_Code 放的位置有很大的影響, 因為牽涉到 compiler的先後順序,因為 VB_Code 在 CS_Code 在前面,所以 CS_Code可以叫用 VB_Code下的程式,但是 VB_Code 卻不能叫用 CS_Code 的程式,如果希望 VB_Code可以叫用 CS_Code的程式,就把設定換過來
    <compilation debug="true" defaultLanguage="c#" targetFramework="4.0">
     <codeSubDirectories>
        <add directoryName="CS_Code"/>
<add directoryName="VB_Code"/>
     </codeSubDirectories>
    </compilation>

缺點就是反過來 CS_Code不能使用 VB_Code的程式

基本上,若是舊的程式碼都在VB_Code 那就把 VB_Code 放到前面
More...
darren, 2017/5/10 下午 02:21:54
windows 2008R2 大量工作排程的匯出備份以及匯入
由於工作排程往往有數十個甚至百來個 因此需要一個方法能快速備份及移轉到其他 server 的方法
查了一下,好像也只能這樣做

---- 使用指令把全部排程匯出 ----
參考網址
https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396

schtasks /query /XML > all_tasks.xml  
schtasks /query /FO CSV /V >sched_tasks.csv

** xml 比較有用,可以用來匯入到其他server排程,但還要額外處理才能匯入
** csv 只是用來看看目前有哪些排程 可以用來做報表看看
** 這些是全部排程,還要特別處理把 Microsoft 及其他軟體建的排程移除

--------------------------------------------------------------

----如何匯入工作排程到其他 server --------

** 需再寫程式把 all_tasks.xml 拆解成所有排程的單一 xml
   並且生成指令 bat

** 注意 xml 必須是 UTF-16 (unicode) 
   因為 "schtasks /query /XML > all_tasks.xml"產生 xml 是 ansi 

參考網址
https://serverfault.com/questions/325569/how-do-i-import-multiple-tasks-from-a-xml-in-windows-server-2008
** /TN "排程名稱" --- 排程名稱可以是路徑名 
D:\>schtasks.exe /create /TN "\2016JOB\Global\CountryMonthlyStats" /XML "D:\one_task.xml"
** 下面程式碼只是下面程式碼只是參考 還沒實作過
=====================================

var taskXML = new XmlDocument();
taskXML.Load(@"d:\temp\schedtasksBackup.xml");
var batbody = new StringBuilder();

XmlNodeList tasks = taskXML.DocumentElement.GetElementsByTagName("Task");

string strFileName = "d:\\temp\\Task";

for (int i = 0; i < tasks.Count; i++) {
    string onetaskXML = tasks[i].OuterXml;

    //Create the New File. With a little more extra effort
    //you can get the name from a comment above the task -> 應該把註解裡的名稱抓出
    XmlWriter xw = XmlWriter.Create(strFileName + "_" + (i+1) + ".xml");
    batbody.AppendLine(string.Format("schtasks.exe /create /TN \"{0}\" /XML \"{1}\"", "Task " + (i+1) + " Name", strFileName + "_" + (i+1) + ".xml"));

    //Write the XML
    xw.WriteRaw(onetaskXML.ToString());
    xw.Close();

    // Write a bat to import all the tasks
    var batfile = new System.IO.StreamWriter("d:\\temp\\importAllTasks.bat");
    batfile.WriteLine(batbody.ToString());
    batfile.Close();

}
=====================================

#微軟的排程備份真是有夠爛沒有辦法用介面一鍵搞定


More...
darren, 2017/5/5 下午 12:07:30
Post File With C#
Post 的資料好像會變大, 要改 Web.config
<system.web>
    <httpRuntime requestValidationMode="2.0" maxRequestLength="1024000"/>
</system.web>



程式碼如下:

public string UploadFilesToRemoteUrl(string url, string[] files, NameValueCollection formFields = null)
    {
        string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = "multipart/form-data; boundary=" +
                                boundary;
        request.Method = "POST";
        request.KeepAlive = true;

        Stream memStream = new System.IO.MemoryStream();

        var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
                                                                boundary + "\r\n");
        var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
                                                                    boundary + "--");


        string formdataTemplate = "\r\n--" + boundary +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

        if (formFields != null)
        {
            foreach (string key in formFields.Keys)
            {
                string formitem = string.Format(formdataTemplate, key, formFields[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }
        }

        string headerTemplate =
            "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
            "Content-Type: application/octet-stream\r\n\r\n";

        for (int i = 0; i < files.Length; i++)
        {
            memStream.Write(boundarybytes, 0, boundarybytes.Length);
            var header = string.Format(headerTemplate, "uplTheFile", files[i]);
            var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

            memStream.Write(headerbytes, 0, headerbytes.Length);

            using (var fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
            {
                var buffer = new byte[1024];
                var bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    Response.Write("bytesRead: " + bytesRead.ToString() + "<br>");
                    memStream.Write(buffer, 0, bytesRead);
                }
            }
        }

        memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
        request.ContentLength = memStream.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            memStream.Position = 0;
            byte[] tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        }

        try
        {
            using (var response = request.GetResponse())
            {
                Stream stream2 = response.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                return reader2.ReadToEnd();
            }
        }
        catch (Exception ex)
        {
            return (ex.ToString());
            throw;
        }
    }
More...
Bike, 2017/1/12 下午 08:21:09
簡單的 HTTP Relay By MVC.
客戶要求
1. 檔案只能放在 Firewall 內的後台用 Web server (Server A).
2. 使用者只能存取 DMZ 的 Web server (Server B).
3. Server B 只能用 HTTP 通過 Firewall 向 Server A 要資料.(i.e.  Server B 不能掛戴 Server A 的目錄成為虛擬目錄)

所以在 Server B 上面建立了一支程式用 HTTP 的方式讀取 Server A 的檔案再寫出去.

例如, http://ServerB/Upload/test.pdf 會讀取 http://ServerA/Upload/test.pdf 再送到 Client 端

namespace WWW.Controllers
{
    public class UploadController : Controller
    {
        // GET: Upload
        public void Index(string Filename)
        {
            //Create a stream for the file
            Stream stream = null;

            //This controls how many bytes to read at a time and send to the client
            int bytesToRead = 10000;

            // Buffer to read bytes in chunk size specified above
            byte[] buffer = new Byte[bytesToRead];

            string url = "http://admin-dev.nanya.bike.idv.tw/newnanyaback/Upload/" + Filename;

            // The number of bytes read
            try
            {
                //Create a WebRequest to get the file
                HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);

                //Create a response for this request
                HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

                if (fileReq.ContentLength > 0)
                    fileResp.ContentLength = fileReq.ContentLength;

                //Get the Stream returned from the response
                stream = fileResp.GetResponseStream();

                // prepare the response to the client. resp is the client Response
                var resp = HttpContext.Response;

                if (Filename.ToLower().EndsWith(".png") ||
                    Filename.ToLower().EndsWith(".jpg") ||
                    Filename.ToLower().EndsWith(".jpeg") ||
                    Filename.ToLower().EndsWith(".gif")
                    )
                {
                    resp.ContentType = "image";
                }
                else
                {
                    //Indicate the type of data being sent
                    resp.ContentType = "application/octet-stream";

                    //Name the file
                    resp.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(Filename, Encoding.UTF8) + "\"");
                }

                resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());

                int length;
                do
                {
                    // Verify that the client is connected.
                    if (resp.IsClientConnected)
                    {
                        // Read data into the buffer.
                        length = stream.Read(buffer, 0, bytesToRead);

                        // and write it out to the response's output stream
                        resp.OutputStream.Write(buffer, 0, length);

                        // Flush the data
                        resp.Flush();

                        //Clear the buffer
                        buffer = new Byte[bytesToRead];
                    }
                    else
                    {
                        // cancel the download if client has disconnected
                        length = -1;
                    }
                } while (length > 0); //Repeat until no data is read
            }
            finally
            {
                if (stream != null)
                {
                    //Close the input stream
                    stream.Close();
                }
            }
        }
    }
}



但不是這樣就好了, 在 RouteConfig.cs 中要加上:
            routes.MapRoute(
                name: "Upload",
                url: "Upload/{filename}",
                defaults: new { controller = "Upload", action = "Index", filename = UrlParameter.Optional }
            );

此外在 Web.Config 中也要加上:

  <system.webServer>
    <handlers>
      <add name="UrlRoutingHandler_Upload"
           type="System.Web.Routing.UrlRoutingHandler, 
               System.Web, Version=4.0.0.0, 
               Culture=neutral, 
               PublicKeyToken=b03f5f7f11d50a3a"
           path="/Upload/*"
           verb="GET"/>
    </handlers>
  </system.webServer>

參考:
http://stackoverflow.com/questions/5596747/download-stream-file-from-url-asp-net

http://blog.darkthread.net/post-2014-12-05-mvc-routing-for-url-with-filename.aspx
More...
Bike, 2016/12/1 下午 09:34:30
上傳的圖片在顯示時被轉 90 度
這通常是手機或相機拍照時有旋轉造成的.

參考: http://automagical.rationalmind.net/2009/08/25/correct-photo-orientation-using-exif/

程式碼:

    void RotatePic(string pathToImageFile)
    {
        // Rotate the image according to EXIF data
        var bmp = new Bitmap(pathToImageFile);
        var exif = new EXIFextractor(ref bmp, "n"); // get source from http://www.codeproject.com/KB/graphics/exifextractor.aspx?fid=207371

        if (exif["Orientation"] != null)
        {
            RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString());

            if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip of orientation is correct
            {
                bmp.RotateFlip(flip);
                exif.setTag(0x112, "1"); // Optional: reset orientation tag
                bmp.Save(pathToImageFile, ImageFormat.Jpeg);
            }
        }

        bmp.Dispose();
    }

    private static RotateFlipType OrientationToFlipType(string orientation)
    {
        switch (int.Parse(orientation))
        {
            case 1:
                return RotateFlipType.RotateNoneFlipNone;
                break;
            case 2:
                return RotateFlipType.RotateNoneFlipX;
                break;
            case 3:
                return RotateFlipType.Rotate180FlipNone;
                break;
            case 4:
                return RotateFlipType.Rotate180FlipX;
                break;
            case 5:
                return RotateFlipType.Rotate90FlipX;
                break;
            case 6:
                return RotateFlipType.Rotate90FlipNone;
                break;
            case 7:
                return RotateFlipType.Rotate270FlipX;
                break;
            case 8:
                return RotateFlipType.Rotate270FlipNone;
                break;
            default:
                return RotateFlipType.RotateNoneFlipNone;
        }
    }
More...
Bike, 2016/12/1 下午 09:15:00
IIS7, MVC, 404
在 .100 安裝 MVC 專案時, web.config 要記得檢查有沒有設定 UrlRoutingModule, 如下. 否則會出現 404 的錯誤.
 
<system.webServer>
  <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  </modules>
</system.webServer>
More...
Bike, 2016/11/22 上午 06:51:17
機房搬遷注意事項
2016 / 10 / 30 搬機房, 有幾件事沒有做好, 記錄一下:

1. Firewall 沒設定好, 下次要一中兩個人一起設定.

2. 有一個客戶的 DNS 等了一整天才生效, 要檢查所有網站的 TTL 和  Refresh 時間, 最好都在一個小時以內.

3. Email 主機: 有些客戶原來是用 msa.hinet.net 這個 SMTP, 搬到非 Hinet 的機房後就不能寄信了.

4. 某一個客戶的 DNS 沒改好, 因為在自已的 DNS Server 上面看到有記錄, 就誤判是我們代管的, 應該要用 Hinet 或 Google 來確認 NS Record 為何. 已刪除它的 DNS  記錄.

5. 202 的 .8 網路線沒插好, 主機開起來後, 要確認可以從每一個介面 Ping 出去.

6. 新 Firewall , 內部 IP 無法連到 Virtual Server: --> 要由內部 IP 連線到 Virtual Server 測試. 最好是在 hosts 上面都有 127.0.0.1 的設定.

7. 最好不要在下半年換機房, 比較忙, 客戶的活動也比較多.

8. Windows 的 DNS 若是直接修改 DNS 檔案. 因為 SOA 的序號沒有修改, 所以 Client 伺服器要手動重新讀取資料.

9. 要記得改 TWNIC 的 DNS Server設定.
More...
Bike, 2016/11/3 上午 11:05:19
Windows server 2012 / 2008 遠端桌面解除單一連線的設定 (Remote Desk Top)
Steps
 

 

windows 2008 的位置有點不一樣:
 



 
 
More...
Bike, 2016/10/6 上午 11:19:27
在 PDF 加浮水印, 用 iTextSharp
找了兩三篇文章再加一點修正才組出來的,  記錄一下, 要用 iTextSharp 哦.

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

---
 
            string oldFile = Server.MapPath("/Content/PDF/300000419_20160929162658862.pdf"); //"oldFile.pdf";
            string newFile = oldFile.Replace(".pdf", "_New11.pdf");

            // open the reader
            PdfReader reader = new PdfReader(oldFile);
            Rectangle size = reader.GetPageSizeWithRotation(1);
            Document document = new Document(size);
            int NumberOfPages = reader.NumberOfPages;

            // open the writer
            FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
            PdfWriter writer = PdfWriter.GetInstance(document, fs);
            document.Open();

            // the pdf content
            PdfContentByte cb = writer.DirectContent;

            string text = "Watermark...";

            string windir = Environment.GetEnvironmentVariable("windir");
            Chunk textAsChunk = new Chunk(text, new Font(BaseFont.CreateFont(windir + "\\Fonts\\mingliu.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), 20, Font.NORMAL, new BaseColor(255,0,0)));

            // create the new page and add it to the pdf
            for (int i = 1; i<= NumberOfPages; i++)
            {
                if(i > 1)
                {
                    document.NewPage();
                }

                ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase(textAsChunk), 0, 0, 0);

                PdfImportedPage page = writer.GetImportedPage(reader, i);
                cb.AddTemplate(page, 0, 0);
            }

            // close the streams and voilá the file should be changed :)
            document.Close();
            fs.Close();
            writer.Close();
            reader.Close();

            Response.Write(newFile + "<br>");
            Response.Write(NumberOfPages + "<br>");
More...
Bike, 2016/9/29 下午 06:23:59
|< …234567891011… >|
頁數 11 / 27 上一頁 下一頁
~ Uwinfo ~