React path to public folder in css background image - html

I am using Create-React-App and I want to add background image for my header section and I am doing this in that way:
background-image: url('~/Screenshot_11.png');
After this I'm getting this error:
./src/styles/main.scss
(./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/sass-loader/lib/loader.js??ref--6-oneOf-5-3!./src/styles/main.scss)
Module not found: You attempted to import
../../../../../../../Screenshot_11.png which falls outside of the
project src/ directory. Relative imports outside of src/ are not
supported.
I've set up homepage in package.json
"homepage": "http://localhost:3000",
In my older projects that works but today I cannot import this correctly.

They have changed that but I don't know why. Working path:
background-image: url('/Screenshot_11.png');
EDIT 2021
For people who think that it doesn't work:
https://codesandbox.io/s/agitated-turing-gsnr3

you can import that image as
import Background from './Screenshot_11.png'
and use
background-image: `url(${Background})`

This still does not work for me with images in the public folder.
UPDATED 19 March 2021
Regarding using of <ROOT/public/images> in .css files.
It appears to be a breaking change (will be considered as a bug?) in create-react-app (react-scripts) package v4.x.
And more precisely in package 'css-loader' v4.x.
3.x branch works OK with that.
Here is the corresponding issue on the github repo:
https://github.com/facebook/create-react-app/issues/9870
(and there are few more actually).
No fixes (yet). (will be?..)
But a few workarounds mentioned there.
Which one to use... it depends on your project, I suppose.
Some of workarounds:
downgrade to react-scripts 3.4.x
don't use url in CSS files :) you still can use in .JSX (inline styles). Or put in .html. They are obviously not processed by css-loader.
reconfigure webpack to add url:false to css-loader options (either eject CRA or use this: https://github.com/gsoft-inc/craco or this: https://github.com/timarney/react-app-rewired
(you can find sample configurations at the github issue page)
use this new feature of css-loader https://github.com/webpack-contrib/css-loader/pull/1264
(released in 5.1.0, current last version is 5.1.3; to use that version you can add the following to the package.json: "resolutions": { "css-loader": "5.1.3" } (at root level) )

Related

visual studio code React does not recognize html

as you see, the HTML content is not colorful, and it cannot autocomplete HTML tag
There are 2 ways to do that.
1) You could manually set the syntax to "Javascript React".
For that click on "Javascript" on the bottom right of your screen:
Then simply enter "react" and select it. After that you should have autocomplete for the html parts inside your render functions.
2) You can instruct VSCode to always open .js files as "javascriptreact". For that go to your settings and copy files.associations over to your local settings. Make sure it looks something like this and save:
"files.associations": {
"*.js": "javascriptreact"
}
Note on that one: This will always set the syntax to "javascriptreact" when you open .js files and might not always be what you want. A better solution would be to generally name react files as myfile.jsx. This way vscode will automatically set the syntax to "javascriptreact".
Hope this helps.
Save the file as .jsx ie (App.jsx) instead of .js
This is because you are saving the file as .js ie App.js.JavaScript files cannot understand HTML tags.
Another alternative is you can save in (.js) but your web pack should be configured in such a way that it should transpile it into .jsx.
For doing refer this - https://github.com/facebook/create-react-app
React understand javascript xml only.

Angular 2 Load CSS background-image from assets folder

My folder structure looks like
-myapp
-assets
-home-page-img
-header-bg.jpg
-src
-app
-home-page
-home-page.component.css
-home-page.component.html
-home-page.component.ts
Inside my home-page.component.css, I have the following
header {
width: 200px;
height: 200px;
background-image: url('/src/assets/home-page-img/header-bg.jpg');
}
My angular-cli.json
"assets": [
"assets",
"favicon.ico"
]
When I run the code, I get
GET http://localhost:4200/src/assets/home-page-img/header-bg.jpg 404 (Not Found)
For demonstrating purpose, If I change background-image to the following, I get a whole different error
background-image: url('assets/home-page-img/header-bg.jpg');
./src/app/home-page/home-page.component.css
Module not found: Error: Can't resolve './assets/home-page-img/header-bg.jpg' in '/Users/JohnSmith/Desktop/my-app/src/app/home-page'
How can I get that image to load?
I use it. Always starting with "/assets/" in CSS and HTML "assets/". And I have no problems. Angular recognizes it.
CSS
.descriptionModal{
background-image: url("/assets/img/bg-compra.svg");
}
HTML
<img src="assets/img/ic-logoembajador-horizontal.svg" alt="logoEmbajador">
try
background-image: url('../../assets/home-page-img/header-bg.jpg');
For background-image: url(/assets/images/foo.png), I have another problem with i18n + base-href, finally I found a workaround solution.
My problem was solved by:
background-image: url(~src/assets/images/foo.png) .
image tag:
<img src="assets/images/foo.jpg" />
Demystifying Angular paths to resources in CSS files
This is not documented nor has anyone to my knowledge written about it.
This is true for Angular 11 but has certainly been around for a while.
(Note: setting --base-href or --deploy-url in ng build has no consequence to the following).
The regular way to include assets in a css file, such as:
background-image: url(/assets/someImage.png);
is with a leading slash. During the build prosses (ng serve or ng build), if angular sees that leading slash, It will ignore that path, meaning it will copy it as is. So the browser will see that path '/assets/someImage.png', and will look for that file starting at the root or as we call it domain. (Note: paths in CSS are relative to the location of the CSS file, but even in CSS a leading slash means looking for the file starting form root).
Angular assumes you put that file In the default assets folder, who's contents are copied as is to the dist folder, and that sits by default in the root, so someDomain.com/assets/someImage.png just works.
However, if for some reason you are trying to do something else, and you remove that slash, a whole new prosses is happening. For example, lets say you now write
background-image: url(assets/someImage.png);
without the slash. (for example when you deploy your app to an inner folder in a domain 'someDomain.com/some-folder/', and assets is in that folder. With the slash it will look for assets in the root, and it not there, its in some-folder. So you remove the slash thinking that it will also copy that code as is and look for assets from where the css file is, which is what the browser will do).
Surprise! Angular this time does not ignore that file path!! it looks for it during build time!! and it doesn't fine it, and you get that annoying error saying angular can't find that file.
So what you do is rewrite that path until angular can find it (in your file system), for example: if your in a deeply nested component
background-image: url(../../../../assets/someImage.png);
And then, boom, it works, but take a look at what happened to your dist folder and to your CSS code.
Angular makes two copies of the someImage.png file. One in the regular assets folder and the other in the root, right next to all the js bundles. And in you CSS file
background-image: url(../../../../assets/someImage.png);
will be rewritten to
background-image: url(someImage.png);
This works, but not exactly nice dist folder structure.
This behaver is same for global style.css or component style that gets injected to the index.html or shadowRoot (ViewEncapsulation.shadowDom)
(Note: in the html templates there are no checks or rewrites)
We can use relative path instead of absolute path:
.logo{
background-image: url('assets/home-page-img/header-bg.jpg');
}
or
.logo{
background-image: url('~src/assets/home-page-img/header-bg.jpg');
}
#Samuel Ivan's answer does not work for me. Maybe because I am developing an internationalization project. At the end, ^ helps me with
.descriptionModal{
background-image: url("^assets/img/bg-compra.svg");
}
And the answer comes from https://github.com/angular/angular-cli/issues/12797
Everyone's missing one thing base-href.
2 Ways:
background-image: url("^assets/img/bg.svg"); [TLDR; just use this]
This will work even if its going to be deployed in a subdirectory rather than root (i.e. you specify a base-href other than the default /).
background-image: url("../assets/img/bg.svg"); [Using relative path]
Using the relative path from the current css,scss,sass file to the actual image in the project folder like. This will work if the assets folder is 1 level above in the directory tree. ("../../" for 2 levels and so on..)
Using a different base-href will not work with this one.
Also, in the build; for the first case this file will be used:
dist/app-name/assets/img/bg.svg
and for the second case the same file will be copied over to the app-name directory and used from there (causing unnecessary redundancy if you already have src/assets in the build assets array in angular.json, which you will in most cases):
dist/app-name/bg.svg
Reference: GH Issue
Try to use this below:
background-image: url('./../assets/home-page-img/header-bg.jpg');
Angular 9+ This Works for me.
.main-bg{
background-image: url("src/assets/main-bg.png");
}
My problem was solved by:
background-image: url(~src/assets/images/foo.png) .
the same with Hieu Tran AGI
You should fix to the file path. My problem was solved:
background-image: url('../assets/img/logo.jpg')

Use Gulp to copy all bower package font files to build directory

I am using the following Gulp task to copy required fonts from the Font Awesome Bower package, this works fine and outputs files like so:
App > Build > Fonts > Font Files
gulp.task('copyfonts', function() {
gulp.src('./bower_components/components-font-awesome/fonts/**/*.{ttf,woff,eof,svg}')
.pipe(gulp.dest('./fonts'));
});
I am trying to refactor this task so that it moves the fonts from any bower package (Bootstrap, for example) using the ** wildcard.
gulp.task('copyfonts', function() {
gulp.src('./bower_components/**/fonts/**/*.{ttf,woff,eof,svg}')
.pipe(gulp.dest('./fonts'));
});
App > Build > Fonts >
Bootstrap > Fonts > Font Files
Font-Awesome > Fonts > Font Files
TL;DR
Using my second method is copying the files as shown above, copying over the package folder and moving that with a 'fonts' folder as a child. Could anyone help show me where I have gone wrong...
I'm a little late to the party here, but for anyone that stumbles upon this in the future: I believe you have a typo in your font glob: eof should be eot.
gulp.src('./bower_components/**/fonts/**/*.{ttf,woff,eof,svg}')
should be
gulp.src('./bower_components/**/fonts/**/*.{ttf,woff,eot,svg}')
Not the best idea to always rely that a package will keep fonts in specific folders, those things can change.
Possibly you're missing another /**/ before fonts (one folder level). Or why all those checks, you know what extensions fonts will have, perhaps add wildcard like **/*.{ttf,woff,eof,svg}
Have you ever tried managing it with gulp-main-bower-files? https://github.com/ck86/main-bower-files
you can test this task
i worked by it
gulp.task('copyfonts', () =>
gulp.src('./app/assets/fonts/*')
.pipe(gulp.dest('./dist/assets/fonts'))
);
I ran into this same issue. After running my gulp builds, my fonts never successfully copied to my dest/fonts folder. The issue was inside my gulp.js file on these lines:
function fonts() {
return src('app/fonts/**/*.{eot,svg,ttf,woff,woff2}')
.pipe($.if(!isProd, dest('.tmp/fonts'), dest('dist/fonts')));
};
After editing the last line, my fonts successfully copied over!
function fonts() {
return src('app/fonts/**/*.{eot,svg,ttf,woff,woff2}')
.pipe(dest('dist/fonts'));
};

How to export Apiary Blueprint as PDF, stand-alone HTML or similar "deliverable"?

We need to export our Apiary Blueprint for task assignment purposes as a self containing "deliverable" like PDF or ZIP or similar. I'm aware of the feature request and the discussion below. Is it possible to "hack" something better than the poor html exporter? Maybe by injecting some css style into the page with chrome? Has somebody found a "good-enough" solution?
Ján Sáreník mentioned aglio, you can make it work locally by the following steps.
Save your API definition markdown (e.g. myfile.md)
Install aglio npm install aglio -g
Start aglio server aglio -i myfile.md -s
Open localhost:3000 and download the HTML file
Hack the HTML by commenting out the <div id="localFile" ...>...</div> warning
Hack the HTML by replacing http://localhost:3000/ with empty string everywhere
Aaand it's done.
You can use https://github.com/danielgtaylor/aglio to render API Blueprint into static HTML files which can be zipped (or maybe also PDF-exported, but I haven't tried).

WkHTMLtoPDF not loading local CSS and images

I've seen multiple questions that are very similar to this one, so I was hesitant at first to post it. But nothing suggested resolved my issue and I can't seem to figure out what's wrong myself.
For a project I made for one client they wanted to ability to convert quotes for their customers (generated using an online form) to PDFs. Simple enough. As the entire project was in PHP, I used the following simple process:
Save the quote as a temporary HTML file
Use WkHTMLtoPDF to convert the HTML file to a PDF
Output this PDF file
Clean up (delete temporary files)
This worked until they changed servers. The new server has a firewall.
At first the PDF conversion step was returning a firewall page saying that the server couldn't make outbound connections. To resolve this I fed the HTML file directly instead of linking to it (/var/www/mysite/temp/18382.html instead of www.example.com/temp/18382.html). This converted the HTML, but the firewall prevented the loading of CSS and images
I can overcome the CSS by simply embedding it directly in the site instead of linking to it (using the <style> tags), but this doesn't work for images
I tried using relative links first. I changed <img src="http://www.example.com/temp/image.jpg" /> to <img src="./image.jpg" />. This didn't work.
Next I tried <img src="file:///var/www/mysite/temp/image.jpg" /> but this didn't work, either
I read around and look through the WkHTMLtoPDF manual and I tried several different command line arguments like --enable-local-file-access, --enable /var/www/mysite/temp/, and --images but nothing seems to fix it
In my case - wkhtmltopdf version 0.12.2.1 (with patched qt) - adding a base tag to the head section with the absolute path made sure images and css did get loaded.
<html>
<head>
...
<base href="http://www.example.com/">
<link href="/assets/css/style.css" rel="stylesheet">
...
</head>
If your are on linux check the ownership of your images. For windows you will find some info on http://code.google.com/p/wkhtmltopdf/wiki/Usage.
I tried different kind of paths to the image:
<img src="file:///var/www/testpdf/flowers.jpg"><br>
<img src="./flowers.jpg"><br>
<img src="flowers.jpg"><br>
<img src="/var/www/testpdf/flowers.jpg"><br>
all images are showed correct. I didn't use any command line arguments
(only wkhtmltopdf /var/www/testpdf/makepdf.html makepdf.pdf)
For Windows you need to use absolute file system paths in your markup. For instance:
<link href='C:\Projects\Hello\Hello.Web\Content\custom\home.css' rel='stylesheet' type='text/css' />
! not http://localhost/Hello.Web/Content/custom/home.css
In order to have them embed, you can insert base64 encoded images like :
<img src="data:image/png;base64,someBase64content"/>
When a browser renders your HTML, it uses a relative path (sometimes with a URL at the beginning of it) like this:
<img src="/static/images/some_picture.png">
<img src="http://www.example.com/static/images/some_picture.png">
But when WkHTMLtoPDF is running on your server, it's interfacing with your local files directly through the filesystem, not through a web server. So for local files, unlike a browser, WkHTMLtoPDF wants the actual filepath:
<img src="/var/www/myapplication/static/images/some_picture.png">
(This worked for me with Python Flask)
on Windows use path: file:///C:/some/dir/some/file.img (notice the tripple /)
It is may be too late :)
BTW, just add this config into your options in last.
options = {'enable-local-file-access': None}
pdfkit.from_string(html, 'filename.pdf', options=options)
After taking in everyone's kind assistance from here and around the net, I discovered something that worked for me - coding in asp.net (c#).
I needed to access the image by url (not file path), as the original source html still needed to be accessed. Through troubleshooting, I discovered these points.
These flags had to be passed in to the command line process:
"-q -n --disable-smart-shrinking --images --page-size A4"
URL still has to be absolute.
Image must be a jpg! I was originally trying to do a gif, to no avail.
I discovered adding "--enable-local-file-access" didn't help, as it requires '\' slashes in the image path instead of '/' slashes, which doesn't help if you also hope to use the source html (in some browsers). Also, if you need to access the local file system, you need to provide an absolute path, as it reads straight from the root and goes from there.
Hope this helps others.
Cheers
-y
I know this is quite old topic, but I've just faced the same issue and maybe it will help to someone.
I tried different approaches, like css background image and using string as base64 encoded data image. Sometimes it helped, sometimes not - no particular rule I could found.
It turned out that upgrading library wkhtmltopdf solved the problem.
I was using version 0.12.0 and upgraded to 0.12.3
What fixed it for me was removing the references to my CSS files. It turned out I had was setting img { max-height: 100%; } in an otherwise-empty div so that was being interpreted as max-height: 0.
So check out your CSS and there might an issue there. This worked:
<div><img src="image.png"/></div>
And running command line in the directory with image.png:
wkhtmltopdf example.html example.pdf
But this does not:
<div><img src="image.png" style = "max-height: 100%; "/></div>
Because the image gets squished to 0 height. Firefox seems to correct this so it wasn't obvious.
This is probably due to SE Linux or firewall rules that prevent you from going out on the internet and back to your own server. You can update your host file to point calls to your domain back to your machine's home address.
make sure you have the latest version of wkhtmltopdf with patched qt.
you can implement a helper that flask jinja uses it to distinguish if the template is for rendering or only generating pdf, or maybe both.
let' say that tmpl_bind is the data object to bind in the template, add a new key tmpl_bind["pdf"] set it True or False.
when using wkhtmltopdf or pdfkit, add enable-local-file-access to options object.
now create a helper function called static_file
def static_file(filename, pdf=False):
# wkhtmltopdf only read absolute path
if pdf:
basedir = os.path.abspath(app.root_path)
return "".join([basedir, "/static/", filename])
else:
return url_for('static', filename = filename)
as we say, wkhtmltopdf for some os only read files when you include their absolute path. Note that you may add or remove parts from the app.root_path, according to your app structure, but this will work in most of cases.
in app configuration add this line after importing static_file function if it is in another file
app.jinja_env.globals['static'] = static_file
finally, in the template import files, images by calling the static_file helper function
<link href="{{ static('css/style.css', pdf) }}" rel="stylesheet" />
<img src="{{ static('assets/images/logo.svg', pdf) }}" class="logo">
For me the problem was resolved by doing two things:
1: In your app/config/config.yml
- Under the knp_snappy
- For the option temporary_folder write ./
- i.e: temporary_folder: ./
2: Now in your html.twig pages remove the asset and write:
From: <link rel="stylesheet" type="text/css" href="{{ asset('css/default_template.css') }}">
To: <link rel="stylesheet" type="text/css" href="css/default_template.css">
And after that, it worked for me.
Hopefully i've helped somebody. Thank you !
To generate your pdf with your images or styles you need to provide the server path as follows:
<img src="https://upload.wikimedia.org/wikipedia/...image.png" />
<link href="http://localhost:8080/css/file.css" media="all" rel="stylesheet" type="text/css" />
Note this second link, it's the local address to your stylesheet, or could be a remote like the first link. The file path didn't work for me, only the server path to the resource.
Ps: In my situation, I am using spring boot in Intellij IDE and I needed to invalidate cache of IDE and not run in debug mode in order to work, otherwise it may be not update things.
URL of images must be absolute not relative.
Check this working example in a twig template:
<img src="{{ absolute_url(asset('images/example.png')) }}"/>
Just spent a few days on getting a Flask/ Blueprint /static file/ css to be read by wkhtmltopdf, so I thought I'd share what I learned.
Win 7, Flask 0.12 on Python 3.4.4, using Pycharm pro, latest pdfkit and wkhtmltopdf.
download the wkhtmltopdf here
install it -mine installed on:
C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe
right after you import pdfkit into your flask routes.py script ,insert the lines:
path_wkthmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
(note the "r" in the first line here !! )
when you use pdfkit in a route, add ",configuration = config" as an argument, eg:
pdfkit.from_string(html_text, output_filename, configuration = config)
this tells pdfkit where to look for wkhtmltopdf. Yes, you need to do this.
NOW in your flask BASE TEMPLATE add , _external = True to your css route, eg:
(this will keep wkhtmltopdf from throwing error cant find css)
NOW (serious bootstrap template juju warning):
go into your flask /external libraries /site-packages /flask_bootstrap /templates /base.html template and:
a. fix CSS link:
<link href="{{bootstrap_find_resource('css/bootstrap.css', cdn='bootstrap')}}" rel="stylesheet" media="screen">
add "http:" so it looks like:
<link href="http:{{bootstrap_find_resource('css/bootstrap.css', cdn='bootstrap')}}" rel="stylesheet" media="screen">
b. fix JS links:
add "http:" so the JS links look like:
<script src="http:{{bootstrap_find_resource('jquery.js', cdn='jquery')}}"></script>
<script src="http:{{bootstrap_find_resource('js/bootstrap.js', cdn='bootstrap')}}"></script>
and with all this
your flask html to pdf conversion
using pdfkit and wkhtmltopdf
should run without errors.
note: I moved to flask from PHP and if you are a flask-er, please post your solutions up here. The flask community is MUCH smaller than the PHP community so we all have to pitch in.
opt = dict()
opt["orientation"] = "landscape"
opt["enable-local-file-access"] = ""
config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf')
enable local file access to access images