我正在使用abcPdf将HTML报告转换为pdf文件. pdf必须是单个横向A4页面.
你知道是否有办法告诉abcPdf扩展HTML页面以适应pdf中的单个页面?我尝试使用Magnify() method,它会缩放内容,但仍会将其分成页面,即使它适合一页.我一直在摸不着头脑,我想知道是否有人这样做了.
这是我目前正在使用的代码:
public byte[] UrlToPdf(string url,PageOrientation po) { using (Doc theDoc = new Doc()) { // When in landscape mode: // We use two transforms to apply a generic 90 degree rotation around // the center of the document and rotate the drawing rectangle by the same amount. if (po == PageOrientation.Landscape) { // apply a rotation transform double w = theDoc.MediaBox.Width; double h = theDoc.MediaBox.Height; double l = theDoc.MediaBox.Left; double b = theDoc.MediaBox.Bottom; theDoc.Transform.Rotate(90,l,b); theDoc.Transform.Translate(w,0); // rotate our rectangle theDoc.Rect.Width = h; theDoc.Rect.Height = w; // To change the default orientation of the document we need to apply a rotation to the root page object. //By doing this we ensure that every page in the document is viewed rotated. int theDocID = Convert.ToInt32(theDoc.GetInfo(theDoc.Root,"Pages")); theDoc.SetInfo(theDocID,"/Rotate","90"); } theDoc.HtmlOptions.PageCacheEnabled = false; theDoc.HtmlOptions.AddForms = false; theDoc.HtmlOptions.AddLinks = false; theDoc.HtmlOptions.AddMovies = false; theDoc.HtmlOptions.FontEmbed = false; theDoc.HtmlOptions.UseResync = false; theDoc.HtmlOptions.UseVideo = false; theDoc.HtmlOptions.UseScript = false; theDoc.HtmlOptions.HideBackground = false; theDoc.HtmlOptions.Timeout = 60000; theDoc.HtmlOptions.BrowserWidth = 0; theDoc.HtmlOptions.ImageQuality = 101; // Add url to document. int theID = theDoc.AddImageUrl(url,true,true); while (true) { if (!theDoc.Chainable(theID)) break; theDoc.Page = theDoc.AddPage(); theID = theDoc.AddImagetochain(theID); } //Flattening the pages (Whatever that means) for (int i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } return theDoc.GetData(); } }
解决方法
所以这就是我解决这个问题的方法.
首先,我需要将HTML页面的高度传递给pdf生成方法,所以我在页面上添加了这个pdf-ed:
<asp:HiddenField ID="hfHeight" runat="server" />
并在后面的代码中:
protected void Page_Init(object sender,EventArgs e) { if (!IsPostBack) { string scriptKey = "WidhtHeightForPdf"; if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptKey)) { StringBuilder sb = new StringBuilder(); sb.AppendLine("<script>") .AppendLine("document.getElementById('" + hfHeight.ClientID + "').value = document.body.clientHeight;") .AppendLine("</script>"); Page.ClientScript.RegisterStartupScript(typeof(Page),scriptKey,sb.ToString()); } } }
现在,当我调用pdf生成方法时,我可以将它传递给HTML的高度.一旦我达到高度,就可以计算pdf“viewport”的宽度,使得高度适合pdf页面:
int intHTMLWidth = height.Value * Convert.ToInt32(theDoc.Rect.Width / theDoc.Rect.Height);
然后通过theDoc的HtmlOptions指定BrowserWidth参数:
theDoc.HtmlOptions.BrowserWidth = intHTMLWidth;
或者将URL添加到theDoc时:
int theID = theDoc.AddImageUrl(url,intHTMLWidth,true);
编辑:这解决了这个问题,所以我打算将它标记为答案.现在接下来要做的是根据HTML的宽度和高度在protrait或横向模式下创建pdf,以便在pdf页面上使用最大空间.