Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

using font-face #24

Closed
rivkawaxman opened this issue Jan 25, 2018 · 10 comments
Closed

using font-face #24

rivkawaxman opened this issue Jan 25, 2018 · 10 comments

Comments

@rivkawaxman
Copy link

rivkawaxman commented Jan 25, 2018

I am trying to include a font from a ttf file.
I put the ttf file in the wwwroot folder of my project and i have this in my css in my html file:
@font-face {
font-family: 'MICR';
src: url("micrenc.ttf") format("truetype");
font-weight: normal;
font-style: normal;
}
and this on the line that needs the font:
style="font-family: 'MICR'; font-size: 30px;

The pdf file does that is created does even not include the text that is supposed to be in that font.
(when i render this file in my browser, i do see the text and in the specified font)

@rdvojmoc
Copy link
Owner

Can you try with other font format than .ttf, for example ,woff? Look at this issue

@rivkawaxman
Copy link
Author

Thanks. However that did not work for me. Am I putting the font file in the right place?

@rdvojmoc
Copy link
Owner

rdvojmoc commented Jan 29, 2018

Please prepare reproducible project and I could take a look.

@rivkawaxman
Copy link
Author

Ok here is a test project which resembles my project
https://github.com/rivkawaxman/pdf_convert
Thank you.

@rdvojmoc
Copy link
Owner

Replace your Get method with this one:

public async Task<IActionResult> Get()
        {
            await Task.CompletedTask;

            string cssPath = @"file:///" + _hostingEnvironment.ContentRootPath + @"\wwwroot\fonts.css";

            string html = "<!DOCTYPE html>" +
                          "<html lang = \"en\">" +
                               "<head>" +
                                    "<meta charset = \"UTF-8\">" +
                                    "<title> Check </title>" +
                                    "<link href='" + cssPath + "' rel='stylesheet' type='text/css' media='screen'>" +
                               "</head>" +
                              "<body>" +
                                    "<div style = \"text-align: center; margin-top:16px;\">" +
                                        "<p style=\"font-family: 'MICR Encoding', sans-serif; font-size: 30px;\"> 235 384756  13425346 9877</p>" +
                                    "</div>" +
                                    "<div style = \"text-align: center; margin-top:16px;\">" +
                                        "<p style=\"font-size: 30px;\"> This line doesn not have a font specified</p>" +
                                    "</div>" +
                              "</body>" +
                          "</html>";
            

            var pdf = new HtmlToPdfConverterService(_converter).Convert(html);
            var path = Path.Combine(_hostingEnvironment.WebRootPath, "micr.pdf");
            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                fs.Write(pdf, 0, pdf.Length);
            }
            return Ok();
        }

As far I know wkhtmltopdf doesn't support relative paths for that reason I added cssPath variable to tell where to look for css file.

In wwwroot create fonts.css and paste this code:

@font-face {
    font-family: 'MICR Encoding';
    font-style: normal;
    font-weight: normal;
    src: url(./micrenc.woff) format('woff');
}

Here is the result of the conversion.

@rivkawaxman
Copy link
Author

Thank you so much! It's working!

@kgrosvenor
Copy link

kgrosvenor commented Nov 21, 2018

Is this a cross platform solution @rivkawaxman i.e linux, mac?

@ghost
Copy link

ghost commented Jan 22, 2020

I tried the solution, using external css, but it's not working for me.
I have a method that generates the html with internal css(tried it with external css too).
If I create a basic html page using the html content generated, the font is used.
The problem is that the pdf doesn't generate using the customFont(as the HTML does), it uses the next one, Arial.

@font-face{
                  font-family: 'customFont';
                  font-style: normal;
                  font-weight: normal;
                  src:url("C:/Users/user/Path/SometOtherPath/customFont.woff"); 
                  // Absolute path for internal css
                  // Relative path for external css 
}
body{
        font-family: 'customFont', Arial, Helvetica, sans-serif;
        font-size: 18px;
}

Is there anything I am missing?

EDIT:
Weirdly enough, if I use a link reference to a css file, it works. That means I am not doing something right with the local css.

@hamedapp
Copy link

hamedapp commented Aug 5, 2020

Replace your Get method with this one:

public async Task<IActionResult> Get()
        {
            await Task.CompletedTask;

            string cssPath = @"file:///" + _hostingEnvironment.ContentRootPath + @"\wwwroot\fonts.css";

            string html = "<!DOCTYPE html>" +
                          "<html lang = \"en\">" +
                               "<head>" +
                                    "<meta charset = \"UTF-8\">" +
                                    "<title> Check </title>" +
                                    "<link href='" + cssPath + "' rel='stylesheet' type='text/css' media='screen'>" +
                               "</head>" +
                              "<body>" +
                                    "<div style = \"text-align: center; margin-top:16px;\">" +
                                        "<p style=\"font-family: 'MICR Encoding', sans-serif; font-size: 30px;\"> 235 384756  13425346 9877</p>" +
                                    "</div>" +
                                    "<div style = \"text-align: center; margin-top:16px;\">" +
                                        "<p style=\"font-size: 30px;\"> This line doesn not have a font specified</p>" +
                                    "</div>" +
                              "</body>" +
                          "</html>";
            

            var pdf = new HtmlToPdfConverterService(_converter).Convert(html);
            var path = Path.Combine(_hostingEnvironment.WebRootPath, "micr.pdf");
            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                fs.Write(pdf, 0, pdf.Length);
            }
            return Ok();
        }

As far I know wkhtmltopdf doesn't support relative paths for that reason I added cssPath variable to tell where to look for css file.

In wwwroot create fonts.css and paste this code:

@font-face {
    font-family: 'MICR Encoding';
    font-style: normal;
    font-weight: normal;
    src: url(./micrenc.woff) format('woff');
}

Here is the result of the conversion.

Works for me

@sangib58
Copy link

In my case i am not able to use font family. Tried in possible all ways(internal css, external css, internal css) but nothing worked.Other css properties are working perfectly.I am using a method to get html. Thanks in advance.

public ActionResult CreatePDF(int id)
{
try
{
string host=Request.Scheme+"://"+Request.Host;
var objGenerator=new CertificateGenerator(_context);

            var globalSettings = new GlobalSettings
            {
                ColorMode = ColorMode.Color,
                Orientation = Orientation.Landscape,
                PaperSize = PaperKind.A4Small,
                Margins = new MarginSettings { Top = 10 },
                DocumentTitle = "",
            };
            var objectSettings = new ObjectSettings
            {
                PagesCount = true,
                HtmlContent =objGenerator.GetHTMLString(id,host),
                //WebSettings = { DefaultEncoding = "utf-8"},
                //WebSettings = { DefaultEncoding = "utf-8",LoadImages=true, UserStyleSheet =  Path.Combine(Directory.GetCurrentDirectory(), @"Resources","Assests", "styles.css") },
                //HeaderSettings = { FontName = FontName, FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                //FooterSettings = { FontName = FontName, FontSize = 9, Line = true, Center = "This is report footer for testing." },    
            };
            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects = { objectSettings }
            };
            var file = _converter.Convert(pdf);
            return File(file, "application/pdf");
        }
        catch (System.Exception)
        {        
            throw;
        }
    }

public string GetHTMLString(int id,string host)
{
var cssPath=Path.Combine(Directory.GetCurrentDirectory(), @"Resources","Assests", "styles.css");
var objCertificate=_context.CertificateTemplates.FirstOrDefault(q=>q.CertificateTemplateId==id);
var sb = new StringBuilder();
sb.Append(@"


<title>Certificate</title>
<style>
body {background-image: url("
+host+objCertificate.BackgroundImagePath+")};background-repeat: no-repeat;</style>");
if(objCertificate.TopLeftImagePath.Length>10 || objCertificate.TopRightImagePath.Length>10)
{
sb.Append(@"

");
if(objCertificate.TopLeftImagePath.Length>10)
{
sb.Append(@"Left Logo");
}
if(objCertificate.TopRightImagePath.Length>10)
{
sb.Append(@"Right Logo");
}
sb.Append(@"
");
}
sb.Append(@"
"+objCertificate.Title+"
"+objCertificate.Heading+"
"+objCertificate.MainText+"
");
if(objCertificate.LeftSignatureImagePath.Length>10 || objCertificate.RightSignatureImagePath.Length>10)
{
sb.Append(@"
");
if(objCertificate.LeftSignatureImagePath.Length>10)
{
sb.Append(@"Left Signature");
}
if(objCertificate.RightSignatureImagePath.Length>10)
{
sb.Append(@"Right Signature");
}
sb.Append(@"
");
}
if(objCertificate.LeftSignatureText.Length>5 || objCertificate.RightSignatureText.Length>5)
{
sb.Append(@"
");
if(objCertificate.LeftSignatureText.Length>5)
{
sb.Append(@"
");
}
if(objCertificate.RightSignatureText.Length>5)
{
sb.Append(@"
");
}
sb.Append(@"
");
}
if(objCertificate.LeftSignatureText.Length>5 || objCertificate.RightSignatureText.Length>5)
{
sb.Append(@"
");
if(objCertificate.LeftSignatureText.Length>5)
{
sb.Append(@""+objCertificate.LeftSignatureText+"");
}
if(objCertificate.RightSignatureText.Length>5)
{
sb.Append(@""+objCertificate.RightSignatureText+"");
}
sb.Append(@"
");
}
sb.Append(@"
");
if(objCertificate.BottomMiddleImagePath.Length>10)
{
sb.Append(@"Bottom Image");
}
sb.Append(@"TAPAS"+(objCertificate.CertificateTemplateId<10?('0'+objCertificate.CertificateTemplateId):objCertificate.CertificateTemplateId)+"");
sb.Append(@"Printed on "+DateTime.Now+"");
sb.Append(@"
");

        sb.Append(@"      
                        </body>
                    </html>");
        return sb.ToString();
    }

body{
font-family: 'Courier New', Courier, monospace;
}
.title {
text-align: center;
font-size: 40px;
color: black;
padding-bottom: 35px;
}
.heading {
text-align: center;
color: black;
padding-bottom: 25px;
}
.mainText {
/* font-variant: small-caps; */
font-style: oblique;
font-size: 25px;
text-align: center;
color: black;
padding-bottom: 35px;
}
.topImages{
padding-bottom: 120px;
}
.imgTopLeft{
float:left;
max-width: 150px;
max-height: 150px;
}
.imgTopRight{
float:right;
max-width: 150px;
max-height: 150px;
}
.signatureImages{
padding-top: 120px;
}
.hrLeft{
float:left;
width: 300px;
}
.hrRight{
float:right;
width: 300px;
}
.signatureHrTag{
padding-top: 80px;
}
.signatureText{
padding-top: 20px;
}
.textLeft{
float: left;
}
.textRight{
float: right;
}
.bottomText{
padding-top: 250px;
}
.imgBottomLeft{
float:left;
max-width: 150px;
max-height: 150px;
}
.textBottomMiddle{
padding-left: 400px;
}
.textBottomRight{
padding-left: 400px;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants