public async Task Generate(string path) { var creator = new PdfHelper(); await creator.PCLGenaratePdf(path); }
public ReportResult Rotate(int desiredRotation = 90) { Report = PdfHelper.Rotate(Report, desiredRotation); return(this); }
protected override void RefreshMaterial() { ShaftRow.SetParameter(X13); RollerPineRow.SetParameter(D, t); BearingStandRow.SetParameter(Bearing, D); BearingRow.SetParameter(Bearing); SealRow.SetParameter(Bearing); CirclipRow.SetParameter(d1); // Set Length ShaftRow.Length = PdfHelper.Nearest5(A3); RollerPineRow.Length = PdfHelper.Nearest5(L); //Update weight BearingStandRow.Weight = Math.Round((3.14f * ((X24 * X24 - (D1 - 22) * (D1 - 22)) / 4 * 3 + (12 * D1 + 36) / 4 * (X26 - 3)) * 7835) / 1000000000, 2); RollerPineRow.Weight = Math.Round(3.14f * (D * D - (D - 2 * t) * (D - 2 * t)) * PdfHelper.Nearest5(L) * 7835 / 4000000000, 2); ShaftRow.Weight = Math.Round(3.14f * X13 * X13 * PdfHelper.Nearest5(A3) * 7835 / 4000000000, 2); }
public void OtherOnline(string md5, string method) { string uppath = BaseHelper.UpPath; //打印与在线查看 BaseHelper.ViewPdf(method == "print" ? PdfHelper.PdfToStream(uppath + md5, true, null, "mjdrawadm", true, "禁止复印 盖章有效", "minicutdraw.png") : PdfHelper.PdfToStream(uppath + md5, true, null, "mjdrawadm", false, "禁止复印 盖章有效", "minicutdraw.png")); }
private void btnPrintPacs_Click(object sender, EventArgs e) { if (this.ExamList.Rows.Count <= 0) { MessageBoxEx.ShowMessage("没有要打印的报告"); return; } List <string> lstFileList = new List <string>(); List <string> lstExamID = new List <string>(); string szMergeFileName = string.Empty; WorkProcess.Instance.Initialize(this, this.ExamList.Rows.Count, "正在下载检查报告...."); foreach (DataGridViewRow item in this.ExamList.Rows) { if (WorkProcess.Instance.Canceled) { WorkProcess.Instance.Close(); return; } WorkProcess.Instance.Show(item.Index + 1); if (item.Cells[this.colResultStatus.Index].Value.ToString() != "确认报告") { continue; } if (item.Cells[this.colCheckBox.Index].Value != null && item.Cells[this.colCheckBox.Index].Value.ToString().ToLower() == "true" ) { ExamResult examResult = item.Cells[this.colFilePath.Index].Tag as ExamResult; if (examResult != null && !string.IsNullOrEmpty(examResult.FILE_PATH)) { //下载文件 string dstFilePath = string.Format("{0}\\{1}\\{2}\\{3}\\{4}.pdf" , SystemParam.Instance.WorkPath , "temp" , SystemParam.Instance.PatVisitInfo.PATIENT_ID , SystemParam.Instance.PatVisitInfo.VISIT_ID , examResult.EXAM_ID); if (!File.Exists(dstFilePath)) { bool result = ShareFolderRead.Download(examResult.FILE_PATH, dstFilePath); if (!result) { MessageBoxEx.ShowError("报告下载失败"); WorkProcess.Instance.Close(); return; } } lstFileList.Add(examResult.FILE_PATH); lstExamID.Add(examResult.EXAM_ID); } } } WorkProcess.Instance.Close(); if (lstFileList.Count <= 0) { MessageBoxEx.ShowMessage("没有要打印的报告"); return; } szMergeFileName = string.Format("{0}\\temp\\{1}\\{2}\\{3}.pdf" , SystemParam.Instance.WorkPath , SystemParam.Instance.PatVisitInfo.PATIENT_ID , SystemParam.Instance.PatVisitInfo.VISIT_ID , string.Join("_", lstExamID.ToArray())); if (!File.Exists(szMergeFileName)) { bool result = PdfHelper.MergePDFFiles(lstFileList.ToArray(), szMergeFileName); if (!result) { MessageBoxEx.ShowError("报告合并打印失败"); return; } } CommandHandler.Instance.SendCommand("报告查看", this.MainForm, szMergeFileName); }
public byte[] GetCombindFileByteArray(List <byte[]> pdfFiles) { return(PdfHelper.CombindMultiplePdf(pdfFiles)); }
public GiftTemplate(PdfHelper pdfHelper, Document document, IEnumerable <GiftEmployeeEntity> model) { _pdfHelper = pdfHelper; _document = document; _model = model; }
public FileInfo Convert(string jobGuid, FileInfo sourceFile, string destinationExtension, string videoQuality) { if (!renderer.IsValidExtension(sourceFile.Extension)) { throw new NotSupportedException($"Extension '{sourceFile.Extension}' is not supported for rendering"); } var rendererForDestinationExtension = renderer.GetRendererForDestinationExtension(destinationExtension); if (rendererForDestinationExtension == null) { throw new NotSupportedException($"No file renderer for extension '{sourceFile.Extension}' found"); } // If we have a conversion from pdf to pdf we only do an Abby/OCR conversion, if the pdf does not contain text already. using (var sourceDoc = new Doc(sourceFile, jobGuid)) { if (MatchesExtension(sourceFile.Extension, "pdf") && MatchesExtension(destinationExtension, "pdf") && PdfHelper.HasText(sourceDoc)) { Log.Information("PDF already contains a text layer. No need for conversion. Returning source file."); return(sourceFile); } } SetProcessorPathByOutputExtension(rendererForDestinationExtension); // Es wird von einer vorhandenen ABBYY-Installation ausgegangen. // Falls es keine Installation von ABBYY gibt, handelt es sich mit grosser Wahrscheinlichkeit um das Testsystem. // In diesem Fall wird die Quelldatei zurückgegeben if (rendererForDestinationExtension is INeedsAbbyyInstallation) { if (string.IsNullOrWhiteSpace(DocumentConverterSettings.Default.PathToAbbyyFrEngineDll)) { var exception = new Exception("Path to FrEngine.dll not set, giving source file back"); Log.Warning(exception, exception.Message); return(sourceFile); } if (!File.Exists(DocumentConverterSettings.Default.PathToAbbyyFrEngineDll)) { throw new Exception($"Path/file '{DocumentConverterSettings.Default.PathToAbbyyFrEngineDll}' does not exist"); } } var cmd = new RendererCommand { SourceFile = sourceFile, Identifier = jobGuid, VideoQuality = string.IsNullOrEmpty(videoQuality) ? VideoQuality.Default.ToString() : videoQuality, PdfTextLayerExtractionProfile = DocumentConverterSettings.Default.PDFTextLayerExtractionProfile }; Log.Information($"Start to render document {sourceFile} with job id {jobGuid} and extraction profile {cmd.PdfTextLayerExtractionProfile} and video quality {cmd.VideoQuality}"); return(rendererForDestinationExtension.Render(cmd)); }
public IHttpActionResult GeneratePdfUrl(DownloadModel downloadModel) { var url = PdfHelper.GetVehicleTripsPdfUrl(downloadModel); return(Ok(url)); }
public ActionResult Planer() { PdfHelper.MakePdfPlaner(Request); return(null); }
/// <summary> /// Adds aggregate to specified table from export model. /// </summary> /// <param name="table">Destination table for headers</param> /// <param name="model">Export table model</param> /// <param name="rows">Source data for calculate the aggregate</param> /// <param name="specialChars">The special chars</param> /// <param name="aggregateLocation">The aggregate location</param> /// <returns> /// table with /// </returns> public static PdfPTable AddAggregateByLocation(this PdfPTable table, TableModel model, XElement[] rows, char[] specialChars, KnownAggregateLocation aggregateLocation) { SentinelHelper.ArgumentNull(table); SentinelHelper.ArgumentNull(model); var hasAnyAggregate = model.Fields.Any(field => field.Aggregate.Show == YesNo.Yes && field.Aggregate.Location == aggregateLocation); if (!hasAnyAggregate) { return(table); } var fix = model.Parent.Resources.Fixed; var rowsCount = rows.Length; var fields = model.Fields; var attributes = rows.Attributes().ToList(); foreach (var field in fields) { var aggregate = field.Aggregate; if (aggregate.AggregateType == KnownAggregateType.None) { continue; } var style = field.Aggregate.GetStyle(); if (field.Aggregate.Show == YesNo.Yes && field.Aggregate.Location == aggregateLocation) { var formula = new NonTabularFormulaResolver(field.Aggregate); switch (field.FieldType) { #region Field: Field case KnownFieldType.Field: BaseDataFieldModel field1 = field; formula.Data = attributes.Where( attr => attr.Name.LocalName.ToUpperInvariant() .Equals( BaseDataFieldModel.GetFieldNameFrom(field1).ToUpperInvariant())) .Select(n => n.Value); break; #endregion #region Field: Fixed case KnownFieldType.Fixed: var fixedFieldModel = (FixedFieldModel)field; var piecesModel = fix[fixedFieldModel.Pieces]; BaseDataFieldModel field2 = field; var dataList = rows.Select(row => piecesModel.DataSource = row) .Select(entries => piecesModel.ToDictionary()) .Select(entry => entry[BaseDataFieldModel.GetFieldNameFrom(field2)]); formula.Data = dataList; break; #endregion #region Field: Gap case KnownFieldType.Gap: var datalist = new List <string>(); for (var i = 0; i <= rowsCount - 1; i++) { datalist.Add(" "); } formula.Data = datalist; break; #endregion #region Field: Group case KnownFieldType.Group: var groupFieldModel = (GroupFieldModel)field; var groupDataList = new List <string>(); foreach (var row in rows) { groupFieldModel.DataSource = row; var group = groupFieldModel.Value.GetValue(specialChars); groupDataList.Add(@group.FormattedValue); } formula.Data = groupDataList; break; #endregion } table.AddCell(PdfHelper.CreateCell(style.Content.DataType.GetFormattedDataValue(formula.Resolve()))); } else { var emptyStyle = StyleModel.Empty; emptyStyle.Content = style.Content; emptyStyle.Content.DataType = new TextDataTypeModel(); ////emptyStyle.SetOwner(model.Styles); table.AddCell(PdfHelper.CreateCell(style.Content.DataType.GetFormattedDataValue(string.Empty))); } } return(table); }
public static Byte[] BuildCommercialInvoice(string rootPath, string orderNumber, OrderShippingInfoDTO shippingInfo, AddressDTO fromAddress, AddressDTO toAddress, IList <DTOOrderItem> items, string trackingNumber, DateTime shipDate) { var html = File.ReadAllText(Path.Combine(rootPath, "commercial_invoice.html")); var weight = (decimal)shippingInfo.WeightD / (decimal)16; var fromString = fromAddress.FullName + "<br/>" + fromAddress.Address1 + "<br/>" + fromAddress.City + ", " + fromAddress.State + " " + fromAddress.Zip + "<br/>" + fromAddress.Country + "<br/>" + fromAddress.Phone + "<br/>" + fromAddress.BuyerEmail; var toString = toAddress.FinalFullName + "<br/>" + toAddress.FinalAddress1 + "<br/>" + (!String.IsNullOrEmpty(toAddress.FinalAddress2) ? toAddress.FinalAddress2 + "<br/>" : "") + toAddress.FinalCity + ", " + toAddress.FinalState + " " + toAddress.FinalZip + "<br/>" + toAddress.FinalCountry + "<br/>" + toAddress.FinalPhone + "<br/>" + toAddress.BuyerEmail; var currency = shippingInfo.TotalPriceCurrency; var totalPriceInUSD = PriceHelper.RougeConvertToUSD(currency, items.Sum(i => i.ItemPrice)); var lines = String.Empty; foreach (var item in items) { var itemPriceInUSD = PriceHelper.RougeConvertToUSD(currency, item.ItemPrice / item.Quantity); var totalItemsPriceInUSD = PriceHelper.RougeConvertToUSD(currency, item.ItemPrice); lines += String.Format( "<tr><td>Watches</td><td></td><td>US</td><td>{0}</td><td>EA</td><td>{1}</td><td>{2}</td></tr>", item.Quantity, itemPriceInUSD.ToString("0.00") + " USD", //currency, totalItemsPriceInUSD.ToString("0.00") + " USD"); // + currency); } html = html.Replace("{Date}", shipDate.ToString("yyyy-MM-dd")); html = html.Replace("{ShipperRef}", orderNumber); html = html.Replace("{ShipperName}", fromAddress.FullName); html = html.Replace("{ShipperAddress}", fromString); html = html.Replace("{FromContact}", fromAddress.ContactName); html = html.Replace("{ReceiverAddress}", toString); html = html.Replace("{DestinationCountry}", toAddress.FinalCountry); html = html.Replace("{ToContact}", toAddress.FinalFullName); html = html.Replace("{ConsigneeName}", toAddress.FinalFullName); html = html.Replace("{Weight}", weight.ToString("0.00")); html = html.Replace("{Waybill}", trackingNumber); html = html.Replace("{TotalAmount}", totalPriceInUSD.ToString("0.00")); html = html.Replace("{Currency}", "USD");//currency html = html.Replace("{Lines}", lines); var css = File.ReadAllText(Path.Combine(rootPath, "commercial_invoice.css"));; // @".headline{font-size:200%} td { padding:20px }"; return(PdfHelper.BuildPdfFromHtml(html, css, 2)); }
private byte[] generatePrinterFriendlyVersion(byte[] pdfContent, string verificationCode) { var client = Util.GetRestPkiClient(); // The verification code is generated without hyphens to save storage space and avoid copy-and-paste problems. On the PDF generation, // we use the "formatted" version, with hyphens (which will later be discarded on the verification page) var formattedVerificationCode = Util.FormatVerificationCode(verificationCode); // Build the verification link from the constant "VerificationLinkFormat" (see above) and the formatted verification code var verificationLink = string.Format(VerificationLinkFormat, formattedVerificationCode); // 1. Upload the PDF var blob = client.UploadFile(pdfContent); // 2. Inspect signatures on the uploaded PDF var sigExplorer = new PadesSignatureExplorer(client) { Validate = true, DefaultSignaturePolicyId = StandardPadesSignaturePolicies.Basic, SecurityContextId = StandardSecurityContexts.PkiBrazil, }; sigExplorer.SetSignatureFile(blob); var signature = sigExplorer.Open(); // 3. Create PDF with verification information from uploaded PDF var pdfMarker = new PdfMarker(client); pdfMarker.SetFile(blob); // Build string with joined names of signers (see method getDisplayName below) var signerNames = Util.JoinStringsPt(signature.Signers.Select(s => getDisplayName(s.Certificate))); var allPagesMessage = string.Format("Este documento foi assinado digitalmente por {0}.\nPara verificar a validade das assinaturas acesse {1} em {2} e informe o código {3}", signerNames, VerificationSiteNameWithArticle, VerificationSite, formattedVerificationCode); // PdfHelper is a class from the Rest PKI Client "fluent API" that helps to create elements and parameters for the PdfMarker var pdf = new PdfHelper(); // ICP-Brasil logo on bottom-right corner of every page (except on the page which will be created at the end of the document) pdfMarker.Marks.Add( pdf.Mark() .OnAllPages() .OnContainer(pdf.Container().Width(1).AnchorRight(1).Height(1).AnchorBottom(1)) .AddElement( pdf.ImageElement() .WithOpacity(75) .WithImage(Util.GetIcpBrasilLogoContent(), "image/png") ) ); // Summary on bottom margin of every page (except on the page which will be created at the end of the document) pdfMarker.Marks.Add( pdf.Mark() .OnAllPages() .OnContainer(pdf.Container().Height(2).AnchorBottom().VarWidth().Margins(1.5, 3.5)) .AddElement( pdf.TextElement() .WithOpacity(75) .AddSection(allPagesMessage) ) ); // Summary on right margin of every page (except on the page which will be created at the end of the document), // rotated 90 degrees counterclockwise (text goes up) pdfMarker.Marks.Add( pdf.Mark() .OnAllPages() .OnContainer(pdf.Container().Width(2).AnchorRight().VarHeight().Margins(1.5, 3.5)) .AddElement( pdf.TextElement() .Rotate90Counterclockwise() .WithOpacity(75) .AddSection(allPagesMessage) ) ); // Create a "manifest" mark on a new page added on the end of the document. We'll add several elements to this mark. var manifestMark = pdf.Mark() .OnNewPage() // This mark's container is the whole page with 1-inch margins .OnContainer(pdf.Container().VarWidthAndHeight().Margins(2.54, 2.54)); // We'll keep track of our "vertical offset" as we add elements to the mark double verticalOffset = 0; double elementHeight; elementHeight = 3; manifestMark // ICP-Brasil logo on the upper-left corner .AddElement( pdf.ImageElement() .OnContainer(pdf.Container().Height(elementHeight).AnchorTop(verticalOffset).Width(elementHeight /* using elementHeight as width because the image is square */).AnchorLeft()) .WithImage(Util.GetIcpBrasilLogoContent(), "image/png") ) // QR Code with the verification link on the upper-right corner .AddElement( pdf.QRCodeElement() .OnContainer(pdf.Container().Height(elementHeight).AnchorTop(verticalOffset).Width(elementHeight /* using elementHeight as width because QR Codes are square */).AnchorRight()) .WithQRCodeData(verificationLink) ) // Header "VERIFICAÇÃO DAS ASSINATURAS" centered between ICP-Brasil logo and QR Code .AddElement( pdf.TextElement() .OnContainer(pdf.Container().Height(elementHeight).AnchorTop(verticalOffset + 0.2).FullWidth()) .AlignTextCenter() .AddSection(pdf.TextSection().WithFontSize(NormalFontSize * 1.6).WithText("VERIFICAÇÃO DAS\nASSINATURAS")) ); verticalOffset += elementHeight; // Vertical padding verticalOffset += 1.7; // Header with verification code elementHeight = 2; manifestMark.AddElement( pdf.TextElement() .OnContainer(pdf.Container().Height(elementHeight).AnchorTop(verticalOffset).FullWidth()) .AlignTextCenter() .AddSection(pdf.TextSection().WithFontSize(NormalFontSize * 1.2).WithText(string.Format("Código para verificação: {0}", formattedVerificationCode))) ); verticalOffset += elementHeight; // Paragraph saying "this document was signed by the following signers etc" and mentioning the time zone of the date/times below elementHeight = 2.5; manifestMark.AddElement( pdf.TextElement() .OnContainer(pdf.Container().Height(elementHeight).AnchorTop(verticalOffset).FullWidth()) .AddSection(pdf.TextSection().WithFontSize(NormalFontSize).WithText(string.Format("Este documento foi assinado digitalmente pelos seguintes signatários nas datas indicadas ({0}):", TimeZoneDisplayName))) ); verticalOffset += elementHeight; // Iterate signers foreach (var signer in signature.Signers) { elementHeight = 1.5; manifestMark // Green "check" or red "X" icon depending on result of validation for this signer .AddElement( pdf.ImageElement() .OnContainer(pdf.Container().Height(0.5).AnchorTop(verticalOffset + 0.2).Width(0.5).AnchorLeft()) .WithImage(Util.GetValidationResultIcon(signer.ValidationResults.IsValid), "image/png") ) // Description of signer (see method getSignerDescription below) .AddElement( pdf.TextElement() .OnContainer(pdf.Container().Height(elementHeight).AnchorTop(verticalOffset).VarWidth().Margins(0.8, 0)) .AddSection(pdf.TextSection().WithFontSize(NormalFontSize).WithText(getSignerDescription(signer))) ); verticalOffset += elementHeight; } // Some vertical padding from last signer verticalOffset += 1; // Paragraph with link to verification site and citing both the verification code above and the verification link below elementHeight = 2.5; manifestMark.AddElement( pdf.TextElement() .OnContainer(pdf.Container().Height(elementHeight).AnchorTop(verticalOffset).FullWidth()) .AddSection(pdf.TextSection().WithFontSize(NormalFontSize).WithText(string.Format("Para verificar a validade das assinaturas, acesse {0} em ", VerificationSiteNameWithArticle))) .AddSection(pdf.TextSection().WithFontSize(NormalFontSize).WithColor(Color.Blue).WithText(VerificationSite)) .AddSection(pdf.TextSection().WithFontSize(NormalFontSize).WithText(" e informe o código acima ou acesse o link abaixo:")) ); verticalOffset += elementHeight; // Verification link elementHeight = 1.5; manifestMark.AddElement( pdf.TextElement() .OnContainer(pdf.Container().Height(elementHeight).AnchorTop(verticalOffset).FullWidth()) .AddSection(pdf.TextSection().WithFontSize(NormalFontSize).WithColor(Color.Blue).WithText(verificationLink)) .AlignTextCenter() ); // Apply marks pdfMarker.Marks.Add(manifestMark); var result = pdfMarker.Apply(); // Return result return(result.GetContent()); }
private static ReplaceResult ReplaceImpl(IInput context, Stream input, string oldText, ReplaceTextOptions options, PdfTable table, float fixedWidth, PointF tableOffset, PdfTableStyle style, YesNo useTestMode) { var outputStream = new MemoryStream(); try { using (var reader = new PdfReader(input)) using (var stamper = new PdfStamper(reader, outputStream)) { var pages = reader.NumberOfPages; for (var page = 1; page <= pages; page++) { var strategy = new CustomLocationTextExtractionStrategy(); var cb = stamper.GetOverContent(page); // Send some data contained in PdfContentByte, looks like the first is always cero for me and the second 100, // but i'm not sure if this could change in some cases. strategy.UndercontentCharacterSpacing = cb.CharacterSpacing; strategy.UndercontentHorizontalScaling = cb.HorizontalScaling; // It's not really needed to get the text back, but we have to call this line ALWAYS, // because it triggers the process that will get all chunks from PDF into our strategy Object var allStrings = PdfTextExtractor.GetTextFromPage(reader, page, strategy); var stringsArray = allStrings.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // The real getter process starts in the following line var textMatchesFound = strategy.GetExtendedTextLocations(oldText, options).ToList(); // MatchesFound contains all text with locations foreach (var match in textMatchesFound) { // Delete tag var bColor = BaseColor.WHITE; cb.SetColorFill(bColor); cb.Rectangle(match.Rect.Left, match.Rect.Bottom, match.Rect.Width, match.Rect.Height); cb.Fill(); // Calculates new rectangle var deltaY = CalculatesVerticalDelta(options, match.Rect); var cellHeight = CalculatesCellHeight(match, oldText, strategy, cb, (string[])stringsArray.Clone(), options, deltaY); var r = BuildRectangleByStrategies(match, oldText, strategy, cb, (string[])stringsArray.Clone(), options); // Width strategy to use var safeFixedWidth = fixedWidth; var useFixedWidth = !fixedWidth.Equals(DefaultFixedWidth); if (useFixedWidth) { if (fixedWidth > r.Width) { safeFixedWidth = r.Width; } } else { safeFixedWidth = r.Width; } // Creates aligned table by horizontal alignment value (this table contains the user table parameter) var outerBorderTable = new PdfPTable(1) { TotalWidth = safeFixedWidth, HorizontalAlignment = Element.ALIGN_LEFT }; var outerCell = PdfHelper.CreateEmptyWithBorderCell(style.Borders); outerCell.MinimumHeight = cellHeight; outerCell.VerticalAlignment = style.Alignment.Vertical.ToVerticalTableAlignment(); outerCell.BackgroundColor = new BaseColor(ColorHelper.GetColorFromString(style.Content.Color)); //table.Table.HorizontalAlignment = Element.ALIGN_LEFT; table.Table.TotalWidth = safeFixedWidth - (outerCell.EffectivePaddingRight + outerCell.EffectivePaddingLeft) * 2; table.Table.LockedWidth = true; // options.StartStrategy.Equals(StartLocationStrategy.LeftMargin) && options.EndStrategy.Equals(EndLocationStrategy.RightMargin); outerCell.AddElement(table.Table); outerBorderTable.AddCell(outerCell); // Creates strategy table (for shows testmode rectangle) var useTestModeTable = new PdfPTable(1) { TotalWidth = safeFixedWidth }; var useTestCell = PdfHelper.CreateEmptyCell(useTestMode); if (table.Configuration.HeightStrategy == TableHeightStrategy.Exact) { useTestCell.FixedHeight = table.Table.TotalHeight; } useTestCell.AddElement(outerBorderTable); useTestModeTable.AddCell(useTestCell); useTestModeTable.WriteSelectedRows(-1, -1, r.X + tableOffset.X, r.Y - tableOffset.Y - deltaY, cb); cb.Fill(); } cb.Stroke(); } stamper.Close(); reader.Close(); } return(ReplaceResult.CreateSuccessResult(new ReplaceResultData { Context = context, InputStream = input, OutputStream = new MemoryStream(outputStream.GetBuffer()) })); } catch (Exception ex) { return(ReplaceResult.FromException( ex, new ReplaceResultData { Context = context, InputStream = input, OutputStream = input })); } }
/// <summary> /// InvoiceXpress <a href="https://invoicexpress.com/api/invoices/documents-pdf">Invoices Pdf</a> Method /// </summary> public static PdfOutputDto Pdf(string apiKey, string accountName, int invoiceId) { return(PdfHelper.Pdf(apiKey, accountName, invoiceId)); }
/// <summary> /// 1. Retrive <a href=''></a> from each html. /// 2. Foreach link, try to fix it. /// 2.1 If the link is full path, just keep it. /// 2.2 If the link is root path(/a/b), just add host in prefix. /// 2.3 If the link is relative path(a/b.html) /// 2.3.1 If the link in TOC, just keep it. /// 2.3.2 If the link NOT in TOC and in Manifest, try to get the canonical url. /// 2.3.3 If the link NOT in TOC and NOT in Manifest, log warning to the invalid link. /// 2.4 Others, keep it as the origin. /// </summary> /// <param name="htmlFilePaths">The htmls' relative path in TOC.</param> public void Transform(IEnumerable <string> htmlFilePaths) { Guard.ArgumentNotNull(htmlFilePaths, nameof(htmlFilePaths)); var tocUrlCache = new UrlCache(_basePath, htmlFilePaths); Parallel.ForEach( htmlFilePaths, htmlFilePath => { var doc = new HtmlDocument(); var currentHtml = PdfHelper.NormalizeFileLocalPath(_basePath, htmlFilePath, false); if (!File.Exists(currentHtml)) { return; } try { var baseDirectory = Path.GetDirectoryName(currentHtml); doc.Load(currentHtml); var tags = doc.DocumentNode.SelectNodes("//a[@href]"); if (tags != null && tags.Count > 0) { bool isTransformed = false; foreach (var tag in tags) { var src = tag.Attributes["href"].Value; if (Uri.TryCreate(src, UriKind.Relative, out Uri uri)) { try { if (Path.IsPathRooted(src)) { if (string.IsNullOrEmpty(_pdfOptions.Host)) { Logger.LogVerbose($"No host passed, so just keep the url as origin: {src}.", htmlFilePath); continue; } if (Uri.TryCreate(_pdfOptions.Host, UriKind.Absolute, out Uri host)) { tag.Attributes["href"].Value = new Uri(host, uri.OriginalString).ToString(); isTransformed = true; } else { Logger.LogVerbose($"The host format:{_pdfOptions.Host} is invalid, so just keep the url as origin: {src}.", htmlFilePath); } } else { // uri.OriginalString may be "virtual-machines-windows.html#abc?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json",then we cannot find the file, so just remove the querystring. var withoutQueryString = uri.OriginalString.RemoveUrlQueryString(); if (uri.OriginalString != withoutQueryString) { tag.Attributes["href"].Value = withoutQueryString; isTransformed = true; } // originalString is used to find the file, so need to remove querystring and bookmark var originalString = uri.OriginalString.RemoveUrlQueryString().RemoveUrlBookmark(); // because when publish to website the url path is toLower so use OrdinalIgnoreCase. string srcInCurrentHtml = new Uri(Path.Combine(baseDirectory, originalString)).LocalPath?.ToLower(); if (originalString.EndsWith(BuildToolConstants.OutputFileExtensions.ContentHtmlExtension, StringComparison.OrdinalIgnoreCase) && !tocUrlCache.Contains(srcInCurrentHtml)) { var conceptual = _manifestUrlCache.Query(srcInCurrentHtml); var assetId = ManifestUtility.GetAssetId(conceptual); if (conceptual == null) { Logger.LogWarning($"Can not find the relative path: {uri.OriginalString} in manifest. So skip to fix the invalid link.", htmlFilePath); continue; } if (!string.IsNullOrEmpty(_pdfOptions.Locale) && !string.IsNullOrEmpty(_pdfOptions.Host)) { // the assetId may has '.html' extension, but we should redirect to the site which should not have '.html' extension, so trim it here. tag.Attributes["href"].Value = string.Format(_pdfOptions.ExternalLinkFormat, assetId.TrimEnd(BuildToolConstants.OutputFileExtensions.ContentHtmlExtension)); isTransformed = true; } else { Logger.LogVerbose($"Host/Locale is null or empty, so just skip to keep the it as origin: {uri.OriginalString}.", htmlFilePath); } } } } catch (Exception ex) { Logger.LogWarning(ex.Message, htmlFilePath); } } } if (isTransformed) { doc.Save(currentHtml); } } } catch (Exception ex) { Logger.LogWarning($"Transfer html not in toc error, details: {ex.Message}", htmlFilePath); } }); }
public MaterialAidTemplate(PdfHelper pdfHelper, Document document, IEnumerable <MaterialIncentivesEmployeeEntity> model) { _pdfHelper = pdfHelper; _document = document; _model = model; }
protected override void OnStartup(StartupEventArgs e) { PdfHelper.InitializeIText(); BootStrapper.InitializeIocContainer(); }
private async void ViewReport() { //Create a new PDF document. PdfDocument doc = new PdfDocument(); //Add a page. PdfPage page = doc.Pages.Add(); Stream fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf"); PdfTemplate header = PdfHelper.AddHeader(doc, "تقرير ذمم الموردين", "Ittezan Pos" + " " + DateTime.Now.ToString()); PdfCellStyle headerStyle = new PdfCellStyle(); headerStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center); page.Graphics.DrawPdfTemplate(header, new PointF()); //Create a PdfGrid. PdfGrid pdfGrid = new PdfGrid(); //String format // PdfFont pdfFont = new PdfTrueTypeFont(fontStream1, 12); //Create a DataTable. DataTable dataTable = new DataTable("EmpDetails"); List <SuplierTotalAmount> customerDetails = new List <SuplierTotalAmount>(); //Add columns to the DataTable dataTable.Columns.Add("ID"); dataTable.Columns.Add("Name"); dataTable.Columns.Add("Address"); dataTable.Columns.Add("Total"); //Add rows to the DataTable. foreach (var item in suppliers) { SuplierTotalAmount customer = new SuplierTotalAmount(); customer.name = item.name; customer.remaining = item.remaining; customer.creditorit = item.creditorit; customer.total_amount = item.total_amount; customerDetails.Add(customer); dataTable.Rows.Add(new string[] { customer.total_amount.ToString(), customer.remaining.ToString(), customer.creditorit.ToString(), customer.name }); } //Assign data source. pdfGrid.DataSource = dataTable; pdfGrid.Headers.Add(1); PdfGridRow pdfGridRowHeader = pdfGrid.Headers[0]; pdfGridRowHeader.Cells[3].Value = "الإسم"; pdfGridRowHeader.Cells[2].Value = "الباقي من فواتير الآجل"; pdfGridRowHeader.Cells[1].Value = "الباقي من الرصيد الإفتتاحي"; pdfGridRowHeader.Cells[0].Value = "الإجمالي"; PdfGridStyle pdfGridStyle = new PdfGridStyle(); pdfGridStyle.Font = new PdfTrueTypeFont(fontStream, 12); PdfGridLayoutFormat format1 = new PdfGridLayoutFormat(); format1.Break = PdfLayoutBreakType.FitPage; format1.Layout = PdfLayoutType.Paginate; PdfStringFormat format = new PdfStringFormat(); format.TextDirection = PdfTextDirection.RightToLeft; format.Alignment = PdfTextAlignment.Center; format.LineAlignment = PdfVerticalAlignment.Middle; pdfGrid.Columns[0].Format = format; pdfGrid.Columns[1].Format = format; pdfGrid.Columns[2].Format = format; pdfGrid.Columns[3].Format = format; pdfGrid.Style = pdfGridStyle; //Draw grid to the page of PDF document. pdfGrid.Draw(page, new Syncfusion.Drawing.Point(0, (int)header.Height + 10), format1); MemoryStream stream = new MemoryStream(); //Save the document. doc.Save(stream); //close the document doc.Close(true); await Xamarin.Forms.DependencyService.Get <ISave>().SaveAndView("تقرير ذمم الموردين .pdf", "application/pdf", stream); }
public FormMain() { InitializeComponent(); pdfHelper = new PdfHelper(); ocrConvertor = new OcrConvertor(); }
private MemoryStream Generate(InvoiceModel invoice) { try { var logo = Image.GetInstance(Logo); var ms = new MemoryStream(); var doc = new Document(PageSize.A4, 40, 40, 40, 40); var pdf = new PdfHelper(doc, ms); var width = doc.Right - doc.Left; var padding = 5f; #region Header pdf.AddImage(logo, absoluteX: doc.Left + padding, absoluteY: doc.Top - 65f); pdf.Text(Labels.LEGAL_NAME, nameFont: BaseFont.TIMES_BOLD, sizeFont: 18, positionX: width * 0.5f, positionY: doc.Top - (padding * 6), align: Element.ALIGN_CENTER); pdf.Text($"CNPJ: {Labels.LEGAL_NUMBER}", nameFont: BaseFont.COURIER_BOLD, sizeFont: 12, positionX: 260f, doc.Top - (padding * 9.5f), align: Element.ALIGN_CENTER); pdf.Text(Labels.ADDRESS, nameFont: BaseFont.HELVETICA_BOLDOBLIQUE, sizeFont: 7, positionX: 260f, positionY: doc.Top - (padding * 12), align: Element.ALIGN_CENTER); pdf.Text($"CEP: {Labels.CEP} Fone: {Labels.PHONE}", nameFont: BaseFont.HELVETICA_BOLDOBLIQUE, sizeFont: 7, positionX: 260f, positionY: doc.Top - (padding * 14), align: Element.ALIGN_CENTER); var collumnAligne = doc.Left + (width * 0.65f) + (padding * 2); pdf.Text(Labels.DESCRIPTION.ToUpper(), nameFont: BaseFont.HELVETICA_BOLD, sizeFont: 8, positionX: width * 0.9f, positionY: doc.Top - (padding * 2.5f), align: Element.ALIGN_CENTER); pdf.Text($"Emissão Data: {invoice.Date:dd/MM/yyyy}", nameFont: BaseFont.HELVETICA, sizeFont: 8, positionX: collumnAligne, doc.Top - (padding * 5), align: Element.ALIGN_LEFT); pdf.Text($"Insc. Municipal N°: {Labels.LEGAL_REGIONAL_NUMBER}", nameFont: BaseFont.HELVETICA, sizeFont: 8, positionX: collumnAligne, doc.Top - (padding * 7), align: Element.ALIGN_LEFT); pdf.Text($"Natureza da Operação: Locação de Veículos", nameFont: BaseFont.HELVETICA, sizeFont: 8, positionX: collumnAligne, doc.Top - (padding * 9), align: Element.ALIGN_LEFT); pdf.Text($"Série: ÚNICA", nameFont: BaseFont.HELVETICA, sizeFont: 8, positionX: collumnAligne, doc.Top - (padding * 11), align: Element.ALIGN_LEFT); pdf.Text($"N°: {invoice.Number.PadLeft(5, '0')}", nameFont: BaseFont.HELVETICA_BOLD, sizeFont: 12, positionX: width * 0.9f, doc.Top - (padding * 14), align: Element.ALIGN_CENTER); #endregion Header #region Client var aligneLeft = doc.Left + 10; pdf.Text($"Nome do Sacado: {invoice.Client.Name}", BaseFont.HELVETICA, 10, aligneLeft, doc.Top - 95, align: Element.ALIGN_LEFT); pdf.Text($"Endereço: {invoice.Client.Address.Street}, {invoice.Client.Address.Number}", BaseFont.HELVETICA, 10, aligneLeft, doc.Top - 110, align: Element.ALIGN_LEFT); pdf.Text($"Município: {invoice.Client.Address.Region}", BaseFont.HELVETICA, 10, aligneLeft, doc.Top - 125, align: Element.ALIGN_LEFT); pdf.Text($"Estado: {invoice.Client.Address.State}", BaseFont.HELVETICA, 10, width * 0.55f, doc.Top - 125, align: Element.ALIGN_LEFT); pdf.Text($"CEP: {invoice.Client.Address.ZipCode}", BaseFont.HELVETICA, 10, width * 0.75f, doc.Top - 125, align: Element.ALIGN_LEFT); pdf.Text($"CNPJ: {invoice.Client.LegalNumber}", BaseFont.HELVETICA, 10, aligneLeft, doc.Top - 140, align: Element.ALIGN_LEFT); pdf.Text($"Insc. Municipal N°: {invoice.Client.RegionalLegalNumber}", BaseFont.HELVETICA, 10, width * 0.45f, doc.Top - 140, align: Element.ALIGN_LEFT); #endregion Client pdf.Text("VALOR REFERENTE POR EXTENSO:", BaseFont.HELVETICA_BOLD, 10, aligneLeft, doc.Top - 162, align: Element.ALIGN_LEFT); pdf.BigTextLeftColumn(invoice.Total.DecimalToExtenso(), doc.Left + padding, doc.Top - 230, width, 50f, nameFont: BaseFont.HELVETICA, sizeFont: 10, align: Element.ALIGN_CENTER); pdf.BigTextLeftColumn(string.Format(Labels.MESSAGE, Labels.LEGAL_NAME), doc.Left + padding, doc.Top - 275, width, 50f, nameFont: BaseFont.HELVETICA, sizeFont: 12); var col1 = doc.Left + (width * 0.25f); var col2 = doc.Left + (width * 0.65f); var col3 = doc.Left + (width * 0.75f); var col4 = doc.Left + (width * 0.9f); var header = doc.Top - 280; pdf.Text("Item Descrição", BaseFont.HELVETICA_BOLD, 10, col1, header, align: Element.ALIGN_CENTER); pdf.Text("Quant", BaseFont.HELVETICA_BOLD, 10, col2, header, align: Element.ALIGN_CENTER); pdf.Text("Vl.Unitário", BaseFont.HELVETICA_BOLD, 10, col3, header, align: Element.ALIGN_CENTER); pdf.Text("Valor", BaseFont.HELVETICA_BOLD, 10, col4, header, align: Element.ALIGN_CENTER); #region Items header -= 15; foreach (var item in invoice.Products) { header -= 15; pdf.Text(item.Description, BaseFont.COURIER, 10, aligneLeft, header, align: Element.ALIGN_LEFT); pdf.Text(item.Quantity.ToString(), BaseFont.HELVETICA, 10, col2, header, align: Element.ALIGN_CENTER); pdf.Text(item.UnitaryValue.FormatMoneyPtBr(), BaseFont.HELVETICA, 10, col3, header, align: Element.ALIGN_CENTER); pdf.Text(item.TotalValue.FormatMoneyPtBr(), BaseFont.HELVETICA, 10, col4, header, align: Element.ALIGN_CENTER); } #endregion Items #region Bancary pdf.Text($"Período do Serviço:", BaseFont.COURIER_BOLD, 10, aligneLeft, doc.Bottom + 340, align: Element.ALIGN_LEFT); pdf.Text($"{invoice.ServicePeriod}", BaseFont.COURIER_BOLD, 10, aligneLeft + 40, doc.Bottom + 330, align: Element.ALIGN_LEFT); pdf.Text($"Dados do Banco", BaseFont.COURIER_BOLD, 10, aligneLeft, doc.Bottom + 320, align: Element.ALIGN_LEFT); pdf.Text($"Banco: ITAU", BaseFont.COURIER_BOLD, 10, aligneLeft, doc.Bottom + 310, align: Element.ALIGN_LEFT); pdf.Text($"Agência: 6385", BaseFont.COURIER_BOLD, 10, aligneLeft, doc.Bottom + 300, align: Element.ALIGN_LEFT); pdf.Text($"Conta Corrente: 56230-8", BaseFont.COURIER_BOLD, 10, aligneLeft, doc.Bottom + 290, align: Element.ALIGN_LEFT); pdf.Text($"N° do Empenho: {invoice.Commitment}", BaseFont.COURIER_BOLD, 10, aligneLeft, doc.Bottom + 280, align: Element.ALIGN_LEFT); pdf.Text($"Observações:", BaseFont.COURIER_BOLD, 10, doc.Left + (width * 0.45f) + padding, doc.Bottom + 335, align: Element.ALIGN_LEFT); pdf.BigTextLeftColumn(invoice.Observation, doc.Left + (width * 0.45f) + padding, doc.Bottom + 265, width * 0.50f, 60f, sizeFont: 10); #endregion Bancary #region Legal Description pdf.Text(Labels.INVOICE_FUNCTION, BaseFont.HELVETICA_BOLD, 15, doc.Left + (width * 0.75f) / 2, doc.Bottom + 220, align: Element.ALIGN_CENTER); pdf.Text(Labels.LEGAL_DESCRIPTION, BaseFont.HELVETICA_OBLIQUE, 11, doc.Left + (width * 0.75f) / 2, doc.Bottom + 190, align: Element.ALIGN_CENTER); pdf.Text("VALOR TOTAL", BaseFont.HELVETICA_BOLD, 15, doc.Left + (width * 0.875f), doc.Bottom + 220, align: Element.ALIGN_CENTER); pdf.Text($"{invoice.Total.FormatMoneyPtBr()}", BaseFont.HELVETICA, 11, doc.Left + (width * 0.875f), doc.Bottom + 190, align: Element.ALIGN_CENTER); #endregion Legal Description #region Footer var line = doc.Bottom + 10; collumnAligne = doc.Left + 5; pdf.Text($"Recebi(emos) da {Labels.LEGAL_NAME} os serviços constantes nesta", BaseFont.HELVETICA, 15, collumnAligne, line + 95, align: Element.ALIGN_LEFT); pdf.Text($"{Labels.DESCRIPTION} - Série ÚNICA N°: {invoice.Number.PadLeft(5, '0')}", BaseFont.HELVETICA, 15, collumnAligne, line + 75, align: Element.ALIGN_LEFT); pdf.Text("Data: _____/_____/__________", BaseFont.HELVETICA, 15, pdf.CenterX, line + 40, align: Element.ALIGN_CENTER); pdf.Text("Assinatura: _______________________________", BaseFont.HELVETICA, 15, pdf.CenterX, line + 10, align: Element.ALIGN_CENTER); #endregion Footer #region Rectaggles var heigthHeader = 80f; pdf.RoundRectangle(xInit: doc.Left, yInit: doc.Top - heigthHeader, width: (width * 0.65f) + padding, height: heigthHeader, radius: 2f); pdf.RoundRectangle(xInit: doc.Left + (width * 0.65f) + padding, yInit: doc.Top - heigthHeader, width: (width * 0.35f) - padding, height: heigthHeader, radius: 2f); var heigthClient = 65f; pdf.RoundRectangle(xInit: doc.Left, yInit: doc.Top - (heigthClient + heigthHeader) - 2, width: width, height: heigthClient, radius: 2f); var heigthExtension = 60f; pdf.RoundRectangle(xInit: doc.Left, yInit: doc.Top - (heigthClient + heigthHeader + heigthExtension) - 4, width: width, height: heigthExtension, radius: 2f); var heigthMessage = 50f; pdf.RoundRectangle(xInit: doc.Left, yInit: doc.Top - (heigthClient + heigthHeader + heigthExtension + heigthMessage) - 6, width: width, height: heigthMessage, radius: 2f); var heigthItems = 145f; pdf.RoundRectangle(xInit: doc.Left, yInit: doc.Top - (heigthClient + heigthHeader + heigthExtension + heigthMessage + heigthItems) - 8, width: width, height: heigthItems, radius: 2f); var heigthBancary = 80f; pdf.RoundRectangle(xInit: doc.Left, yInit: doc.Bottom + 272, width: width * 0.45f, height: heigthBancary, radius: 2f); pdf.RoundRectangle(xInit: doc.Left + (width * 0.45f), yInit: doc.Bottom + 272, width: width * 0.55f, height: heigthBancary, radius: 2f); var heigthLegalDescription = 99f; pdf.RoundRectangle(xInit: doc.Left, yInit: doc.Bottom + 170, width: width * 0.75f, height: heigthLegalDescription, radius: 2f); pdf.RoundRectangle(xInit: width * 0.75f + doc.LeftMargin, yInit: doc.Bottom + 170, width: width * 0.25f, height: heigthLegalDescription, radius: 2f); pdf.Line(doc.Bottom + 150); pdf.Line(doc.Top - 290); pdf.RoundRectangle(xInit: doc.Left, yInit: doc.Bottom, width: width, height: doc.Bottom + 92, radius: 2f); #endregion Rectaggles doc.Close(); var msInfo = ms.ToArray(); ms.Write(msInfo, 0, msInfo.Length); ms.Position = 0; return(ms); } catch (InvalidOperationException) { throw new InvalidOperationException($""); } }
private void CreatePDF(X18J52 x18J52, string hpzl, byte[] qrcode) { PdfHelper pdfHelper = new PdfHelper(); Document doc = pdfHelper.CreateDocumentA4(); MemoryStream memoryStream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream); try { doc.Open(); doc.NewPage(); BaseFont ArialFont = BaseFont.CreateFont("STZHONGS.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); iTextSharp.text.Font BoldFont = new iTextSharp.text.Font(ArialFont, 11, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black)); //二维码 iTextSharp.text.Image img = pdfHelper.CreateImage(qrcode, 100, 100f); img.SetAbsolutePosition(AppHelper.PointSetting.X_QRCode, AppHelper.PointSetting.Y_QRCode); doc.Add(img); PrintPoint print = AppHelper.PointSetting; PdfContentByte pb = writer.DirectContent; pb.BeginText(); pb.SetFontAndSize(ArialFont, 9); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, DateTime.Now.ToString("yyyy"), print.X_Year, print.Y_Year, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, DateTime.Now.ToString("MM"), print.X_Month, print.Y_Month, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, DateTime.Now.ToString("dd"), print.X_Day, print.Y_Day, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, x18J52.hphm, print.X_PlateNo, print.Y_PlateNo, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, x18J52.syr, print.X_Owner, print.Y_Owner, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, hpzl, print.X_PlateType, print.Y_PlateType, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "", print.X_PlateColor, print.Y_PlateColor, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, x18J52.cllx, print.X_CarType, print.Y_CarType, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, x18J52.clpp1, print.X_CarBrand, print.Y_CarBrand, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, x18J52.clxh, print.X_CarMold, print.Y_CarMold, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, x18J52.ccdjrq, print.X_RegisterDate, print.Y_RegisterDate, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, x18J52.ccrq, print.X_MakeDate, print.Y_MakeDate, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, x18J52.zzl, print.X_Weight, print.Y_Weight, 0); pb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, x18J52.zbzl, print.X_KerbWeight, print.Y_KerbWeight, 0); pb.EndText(); doc.Close(); MemoryStream pdf = new MemoryStream(memoryStream.ToArray()); PDFFile pdfFile = PDFFile.Open(pdf); PrinterSettings settings = new PrinterSettings(); PrintDocument pd = new PrintDocument(); settings.PrinterName = AppHelper.AppSetting.PrinterName; settings.PrintToFile = false; PDFPrintSettings pdfPrintSettings = new PDFPrintSettings(settings); pdfPrintSettings.PageScaling = PageScaling.MultiplePagesPerSheetProportional; pdfPrintSettings.PrinterSettings.Copies = 1; pdfFile.Print(pdfPrintSettings); pdf.Close(); pdf.Dispose(); pdfFile.Dispose(); } catch (Exception ex) { MessageBox.Show("打印异常" + ex.Message); } finally { memoryStream.Dispose(); memoryStream.Close(); writer.Dispose(); doc.Dispose(); doc.Close(); } }
/// <summary> /// 加载主页PDF说明 /// </summary> public void Help() { BaseHelper.ViewPdf(PdfHelper.PdfToStream(Server.MapPath("/Resource/Template/help.pdf"), true, null, null, false, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), "minicutdraw.png")); }
public static HttpResponseInfo Rest_Pdf(string apiKey, string accountName, int simplifiedInvoiceId) { return(PdfHelper.Rest_Pdf(apiKey, accountName, Int32.MaxValue)); }
public ReportResult AddWatermark(string text, BaseFont baseFont) { BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false); Report = PdfHelper.AddWatermark(Report, baseFont, text); return(this); }
/// <summary> /// InvoiceXpress <a href="https://invoicexpress.com/api/proformas/documents-pdf">Proformas Pdf</a> Method /// </summary> public static PdfOutputDto Pdf(string apiKey, string accountName, int proformaId) { return(PdfHelper.Pdf(apiKey, accountName, proformaId)); }
public ReportResult AddPageNumber() { Report = PdfHelper.AddPageNumbers(Report); return(this); }
public static HttpResponseInfo Rest_Pdf(string apiKey, string accountName, int invoiceId) { return(PdfHelper.Rest_Pdf(apiKey, accountName, invoiceId)); }
public TitleTemplate(PdfHelper pdfHelper, Document document) { _pdfHelper = pdfHelper; _document = document; }
public virtual void TestOriginalSizeScaleMode() { String path = PdfHelper.GetDefaultImagePath(); FileInfo file = new FileInfo(path); OcrPdfCreator ocrPdfCreator = new OcrPdfCreator(new CustomOcrEngine()); PdfDocument doc = ocrPdfCreator.CreatePdf(JavaCollectionsUtil.SingletonList <FileInfo>(file), PdfHelper.GetPdfWriter ()); NUnit.Framework.Assert.IsNotNull(doc); ImageData imageData = ImageDataFactory.Create(file.FullName); float imageWidth = GetPoints(imageData.GetWidth()); float imageHeight = GetPoints(imageData.GetHeight()); float realWidth = doc.GetFirstPage().GetPageSize().GetWidth(); float realHeight = doc.GetFirstPage().GetPageSize().GetHeight(); NUnit.Framework.Assert.AreEqual(imageWidth, realWidth, DELTA); NUnit.Framework.Assert.AreEqual(imageHeight, realHeight, DELTA); doc.Close(); }