[英]Adding a Header and a footer in C# with the output from my program
我是C#的新手,我的程序中有一個“保存到文件”選項,可將RichTextBox的輸出保存在Word文檔中,當用戶選擇此選項時,我已使用saveFileDialogue框讓用戶選擇文件名和位置。
我想要的是,每當用戶選擇此選項時,保存輸出的Word文檔都具有預定義的頁眉和頁腳圖像...
非常感謝您的提前幫助!
下面是我的“保存到文件”代碼。
private void menuItem7_Click(object sender, EventArgs e)
{
// Create a SaveFileDialog to request a path and file name to save to.
SaveFileDialog saveFile1 = new SaveFileDialog();
// Initialize the SaveFileDialog to specify the RTF extension for the file.
saveFile1.DefaultExt = "*.rtf";
saveFile1.Filter = "RTF Files|*.rtf";
// Determine if the user selected a file name from the saveFileDialog.
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
// Save the contents of the RichTextBox into the file.
richTextBox1.SaveFile(saveFile1.FileName,
RichTextBoxStreamType.PlainText);
}
}
您為“新手”選擇了一項非常艱巨的任務。 要混合圖像和文本,您將需要一種復雜的格式,例如PostScript,PDF,DocX或RTF。 控制分頁,例如僅指定一次頁眉和頁腳圖像,並使它們自動顯示在每頁的頂部和底部,是一項更加困難的任務。
您沒有給我們足夠的信息來告訴您從哪里開始。 例如,什么是“我的程序”? 像文字處理程序嗎? 您將必須使用System.Drawing.Printing.PrintDocument
類來定義打印文檔,在到達每一頁上的適當位置時繪制頁眉和頁腳,執行行布局,分頁和分頁。 對於專業程序員而言,這是一項艱巨的工作。
還是只想生成另一個程序可以輸出的帶有頁眉和頁腳的文件? 您可以輸出RTF。 規格在這里 。 這是一件容易的事。 您也許可以利用現有的RTF解釋器 。
還是要在屏幕上顯示這些文檔? Han的建議是通過自動化使用現有應用程序,這是一個很好的建議。
將您的任務分解成較小的需求並調查每個需求。
首先,創建一個函數以獲取圖像,寬度和高度並返回rtf:
這是為png
public string GetImage(string path, int width, int height)
{
var stream = new MemoryStream();
var img = Image.FromFile(path);
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
var bytes = stream.ToArray();
var str = BitConverter.ToString(bytes, 0).Replace("-", string.Empty);
var mpic = @"{\pict\pngblip\picw" + img.Width.ToString() + @"\pich" + img.Height.ToString() +
@"\picwgoa" + width.ToString() + @"\pichgoa" + height.ToString() +
@"\hex " + str + "}";
return mpic;
}
現在,您需要將此“圖像”插入rtf中的正確位置。 如果您在記事本中打開rtf文件,您應該會看到類似以下內容:
{\\ rtf1 \\ ansi \\ ansicpg1252 \\ deff0 \\ deflang2057 {\\ fonttbl {\\ f0 \\ fnil \\ fcharset0 Microsoft Sans Serif;}} \\ viewkind4 \\ uc1 \\ pard \\ f0 \\ fs17 MYTEXT \\ par}
如果您想要一種快速而又骯臟的方法,請從richTextBox中獲取rtf到一個字符串中,然后在deflang2057之后插入標題圖像字符串,后跟一個'/ par'來換行。 然后在結尾的'}'之前插入頁腳圖片字符串
像這樣的東西:
// Determine if the user selected a file name from the saveFileDialog.
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
var rtf = richTextBox1.Rtf.Insert(richTextBox1.Rtf.IndexOf("deflang2057") + 11, GetImage(@"c:\a.png", 5, 5) + @"\par");
using (var rtfFile = new StreamWriter(saveFile1.FileName))
{
rtfFile.Write(rtf);
}
}
我希望這可以幫助您入門。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.