Html to pdf convert using Api not setting margin

I am trying to convert html file into pdf. I need to set a margin for every page here. But nothing happened here.

             var apiKey = "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx";
                var apiSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; 

                // Load existing PDF document
                var api = new HtmlApi(apiKey, apiSecret).ConvertApi;
                var result = await api.ConvertAsync("Blankpages.html", "Blankpages.pdf");
                var pdfFilePath = Path.Combine(Environment.CurrentDirectory, "Blankpages.pdf");
                var pdfDocument = new Aspose.Pdf.Document(pdfFilePath);


                // Add top margin to the WorkOrderTemplate
                foreach (Page page in pdfDocument.Pages)
                { 
                    page.PageInfo.Margin = new MarginInfo(left:90, right: 70, top: 90, bottom: 30);
                }


                // Save the changes to the existing PDF file
                pdfDocument.Save(pdfFilePath);

                // Return the modified PDF as a file for download
                var pdfBytes = System.IO.File.ReadAllBytes(pdfFilePath);
                return new FileContentResult(pdfBytes, "application/pdf")
                {
                    FileDownloadName = "ModifiedSample.pdf"
                };

@niku2023

You are using both cloud API and on-premise API. If you want to use cloud API then please try Aspose.PDF Cloud for the HTML to PDF conversion. It provides parameters to set the page margins.

​PUT /pdf​/{name}​/create​/html Convert HTML file (located on storage) to PDF format and upload resulting file to storage.

This is my new code. I have added margin-left: 10px; but its not showing. I am new to this. if you can please correct me with my code

        async Task<byte[]> ITransformHelper.ConvertHtmlToPdf(string htmlDocument, Manifest manifest, string header, string footer, string requestId)
        {
            try
            {
            
            string headerHtml = string.Empty;
            string footerHtml = string.Empty;
            string htmlHeaderPath = "";
            string htmlFooterPath = "";
            string htmlFilePath = "";
            htmlFilePath = manifest.Output.OutputFileName?.Replace(".pdf", ".html");


                if (!string.IsNullOrEmpty(header))
                {
                    PageMargin margin = manifest.Input.PageSetup.PageMargin;

                    // Set the top margin value (in this example, 20 pixels)
                    int topMarginValue = margin.HeaderMargin.Height;

                    // Assuming documentHtml is a complete HTML document with <html>, <head>, and <body> tags
                    string modifiedHtml = htmlDocument.Replace("<body>", $"<body style='margin-top:{topMarginValue}px;'>");
                    File.WriteAllText(htmlFilePath, modifiedHtml);
                }
                else
                {
                    string modifiedHtml = htmlDocument.Replace("<body>", $"<body style='margin-top: 100px; margin-right: 90px; margin-bottom:100px; margin-left: 10px;'>");
                    File.WriteAllText(htmlFilePath, modifiedHtml); 
                }


                var api = new HtmlApi("xxxxxxxx", "xxxxxxxxxx").ConvertApi;
                var result = await api.ConvertAsync(htmlFilePath, manifest.Output.OutputFileName); 

                // Load existing PDF document
                var pdfDocument = new Aspose.Pdf.Document(manifest.Output.OutputFileName);

            byte[] fileBytes = File.ReadAllBytes(manifest.Output.OutputFileName);

            if (File.Exists(htmlFilePath))
            {
                File.Delete(htmlFilePath);
            }

            if (File.Exists(manifest.Output.OutputFileName))
            {
                File.Delete(manifest.Output.OutputFileName);
            }
            if (File.Exists(htmlHeaderPath))
            {
                File.Delete(htmlHeaderPath);
            }

            if (File.Exists(manifest.Template.HeaderTemplate))
            {
                File.Delete(manifest.Template.HeaderTemplate);
            }
            if (File.Exists(htmlFooterPath))
            {
                File.Delete(htmlFooterPath);
            }

            if (File.Exists(manifest.Template.FooterTemplate))
            {
                File.Delete(manifest.Template.FooterTemplate);
            }

            return fileBytes;
            }
            catch (Exception ex)
            {
                throw new BlobDoesNotExistException(string.Format(Properties.Resources.BlobDoesNotExist) + $" Exception : {ex.Message}");
            }
        }

@niku2023

Please find a sample .NET code to convert HTML to PDF using the Aspose.PDF Cloud API. You can set page margins in the conversion.

Secondly, can you please confirm where you got the above code? as it is using both cloud API and on-premise API. Both versions of the APIs need separate licenses.

// instantiate the PdfApi
PdfApi pdfApi = new PdfApi(ClientSecret, ClientId);
string localFolder = "C:/Temp/";
string TempFolder = "Temp";
string name = "Test.zip";
string htmlFileName = "Test.html";            
int marginRight = 5;
int marginLeft = 5;
int marginTop = 5;
int marginBottom = 5;

string resultName = "fromHtml.pdf";

// upload PDF file to cloud storage
var file = System.IO.File.OpenRead(localFolder + name);
await pdfApi.UploadFileAsync(TempFolder+"/"+name, file);

// Convert HTML to PDF file from cloud storage
await pdfApi.PutHtmlInStorageToPdfAsync(resultName, Path.Combine(TempFolder, name), htmlFileName, marginLeft: marginLeft,marginBottom: marginBottom, marginRight: marginRight,marginTop: marginTop, dstFolder: TempFolder);

// Download file Cloud Storage

var actual = await pdfApi.DownloadFileAsync(Path.Combine(TempFolder, resultName), null, null);
var fileStream = System.IO.File.Create(@"C:\Temp\Output.pdf");
actual.CopyTo(fileStream);
fileStream.Close();

@tilal.ahmad
When I call this ** PdfApi pdfApi = new PdfApi(apiKey, apiSecret);** i am getting this error.

System.MissingMethodException: ‘Method not found: ‘Void RestSharp.RestClient.set_BaseUrl(System.Uri)’.’

@niku2023

Please ensure that you have installed the latest version of Aspose.PDF Cloud SDK for .NET from NuGet.

I have installed Aspose.Pdf-Cloud 23.11.0 and Aspose.PDF 23.11.1 But still getting the error

System.MissingMethodException: ‘Method not found: ‘Void RestSharp.RestClient.set_BaseUrl(System.Uri)’.’

@niku2023

Kindly share a sample working project to reproduce the issue.

1 Like

Thanks for the reply. I found the issue. I have many projects in my solution. One had this restsharp nuget. I have removed it. now issue fixed

1 Like

@niku2023

Thanks for your feedback and we are glad to know that your issue is resolved. Please feel free to contact us for any further assistance.