Including style sheets in a PDF in cakePHP - cakephp

I am using dompdf to generate PDFs for some of the views and that is working just fine. The problem is that I cannot include the css files anywhere, and only css included in the <style> tags inside the view itself is taken into consideration.
Here is the controller action:
public function view_pdf($id=null){
ini_set('memory_limit','512M');
$event = $this->Event->findById($id);
$evt_data=new \DateTime($event['Event']['date']);
$this->set('event', $event);
$this->layout='event';
}
Here is the layout:
require_once(APP . 'Vendor' . DS . 'dompdf' . DS . 'dompdf_config.inc.php');
spl_autoload_register('DOMPDF_autoload');
$dompdf = new DOMPDF();
$dompdf->set_paper = 'A4';
$dompdf->load_html(utf8_decode($content_for_layout), Configure::read('App.encoding'));
$dompdf->render();
echo $dompdf->stream('Event.pdf');
And here is the view itself (shortened version):
<style>
div.content-event{
background: gray;
color: black;
padding: 20px;
}
</style>
<div class="content-event" style="margin-bottom: 80px">
<div class="heading">
<div class="row">
<div class="col-md-12">
<h3><?php echo $event['Event']['name']; ?></h3>
</div>
</div>
</div>
I have tried to include the css files in the usual way, like: echo $this->Html->css('event');, in both the view and the layout, but this is just not taking any action.
Any help or guidance is much appreciated.

You can include CSS file like following:-
<link rel="stylesheet" type="text/css" href="<?php echo APP.'webroot'.DS.'css'.DS.'event.css'; ?>" media="all" />
Put your css file into webroot/css folder.

Archana's answer appears to be valid, but I wanted to provide a bit more context. When you load a document using $dompdf->load_html() dompdf has no information about the source of the file. When you provide links to external resources dompdf sets the currently executing file on the local file system as the base path.
Essentially URLs will be parsed in the following manner:
relative URLs (e.g. css/styles.css) will be evaluated relative to the currently executing file
absolute URLs (e.g. /css/styles.css) will be evaluated relative to the file system root
URLs with a domain (e.g. http://example.com/css/styles.css) will be evaluated as written
When you make the following call to HTMLHelper::css:
$this->Html->css('styles')
CakePHP will produce a style reference similar to the following:
<link rel="stylesheet" type="text/css" href="/css/styles.css" />
Based on the parsing rules I outlined above that reference will be read from the filesystem root. And unless you have a root folder called "css" with your stylesheet in it that reference will be invalid. The reason Archana's answer works is that you're providing a path from the root of the file system to the file (e.g. /inet/www/cakesite/app/webroot/css/styles.css).
It's a bit easier to get a handle on external resource references if you specify a domain. In that manner dompdf will access the resource via your web server as would any web browser. This type of reference does require a bit more attention to your dompdf and server configuration.
You might find the following questions helpful on how to construct a URL:
Q: How to get the base Url in cakephp?
Q: base_url in CakePHP

Related

Embedding a react app within a squarespace site

I'm trying to embed a small react app into a squarespace site.
Here's the page: https://www.birdiebreak.com/referral-profile?referralCode=WHUOS
I can get the react app to load just fine but various parts of the site disappear! Specifically the header and any images on the page.
I've tried using the Code widget as well as the Embed widget with both have the same result.
I did try a basic Create React App site to see if the minimal code I built was the problem but got the same issues.
Has anyone managed to do this successfully?
I don't know why exactly, but if I add a script tag into the body referencing my react app <script src="path-to-react/main.buildcode.js" /> parts of the squarespace site just stop loading.
However if instead I add a script loader things work just fine.
<script type="text/javascript">
(function (g, r, head, script) {
head = r.getElementsByTagName("head")[0];
script = r.createElement("script");
script.async = 1;
script.src = "https://birdie-break-develop.azurewebsites.net/static/js/main.d2ee648d.js";
head.appendChild(script);
})(window, document);
</script>
I've had success using a modified version of the Add React to a Website guide in the React docs. Assuming you have access to the source code for your React app, the following steps should work:
Add a Code Block with a single empty div containing a unique ID ('custom-react-root', or whatever you'd like). This is where your React app will render.
Configure your index.js to use this block as the root:
function run() {
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('custom-react-root')
);
}
Run the build command for your build tool to create the minified JS files. (e.g. yarn build)
Wrap the minified JS files in <script> tags, and the CSS file in <style> tags. I wrote a bash script to do this, which includes the following lines:
(
echo "<script>"
cat build/static/js/2.*.chunk.js
echo "</script>"
echo "<script>"
cat build/static/js/main.*.chunk.js
echo "</script>"
echo "<script>"
cat build/static/js/runtime-main.*.js
echo "</script>"
echo "<style>"
cat build/static/css/*.chunk.css
echo "</style>"
) > build/injectable.html
Paste these tags into the Page Header, as described in the SquareSpace docs.

Data file location relative to html when running Azure Maps tutorials locally - atlas.io.read()

Trying to determine how to revise the atlas.ioread() function from the Azure Maps tutorial below to read the data locally on my windows machine.
atlas.io.read(window.location.origin + '/Common/data/Gpx/Route66Attractions.xml')
Does the 'window.location.origins +' work with local files?
I have nested the .xml file similarly to the above string, relative to the html file, however, it does reading the file when the map is launched.
Azure Maps Tutorial:
https://github.com/Azure-Samples/AzureMapsCodeSamples/blob/master/AzureMapsCodeSamples/Spatial%20IO%20Module/Load%20spatial%20data%20(simple).html
That function won't be able to access local files directly as the URL must be a http or https URL. There are a couple of approaches you can take.
If you plan to host the file later, you can host it locally on localhost and then have a URL pointing to it.
If you want to access local files, you will first need to load the file into your app using the file input tag and the FileReader class. Once you have the raw file data (text), you can pass that into the atlas.io.read function and it will process if for you. Here is a simple example:
<!DOCTYPE html>
<html>
<head>
<title>Read Text File</title>
<!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
<link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css" type="text/css" />
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.js"></script>
<!-- Add reference to the Azure Maps Spatial IO module. -->
<script src="https://atlas.microsoft.com/sdk/javascript/spatial/0/atlas-spatial.min.js"></script>
</head>
<body>
<input type="file" name="inputfile" id="inputfile">
<script type="text/javascript">
window.onload = function() {
var input = document.getElementById('inputfile');
input.addEventListener('change', function() {
var fr = new FileReader();
fr.onload = function(){
atlas.io.read(fr.result).then(function(r){
//r is the parsed data. Do something with it.
});
}
fr.readAsText(input.files[0]);
});
});
</script>
</body>
</html>

Add Static resources in spring boot

I am a newbie to spring boot architecture. It says that to let the index pages to find static resources like js, we need to keep it under "src/main/resources/static".
Directory Structure:
Html files: src/main/webapp/WEB-INF/jsp/
js files: src/main/resources/static/js/
This is my index page:
<html ng-app="RollbackApp">
<head>
<title>My Rollback View</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.js"></script>
<script type="text/javascript" src = "js/app.js"></script>
</head>
<body>
<div ng-controller="rollbackController"><p>
<button ng-click="rollback()">RollBack</button>
</p></div>
</body>
</html>
Currently the index page is not able to load my "app.js"
My Mvc config class is as follows:
package com.manoj;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
/**
* Created by manojma on 10/13/2017.
*/
#Configuration
#EnableWebMvc
public class ApplicationWebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/static/");
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".html");
return resolver;
}
}
I am unable to find the reason, why it is not able to find my js files.
Please help me with this.!!
The issue is that your resource handler isn't configured correctly. You've set /resources/static/ as your resource location. However, considering that src/main/resources is put entirely on your classpath, you should leave away the /resources part. Additionally, you should mention that you're looking on your classpath, so you should probably use classpath:/static/.
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/static/");
}
Additionally to that, you've defined the resource handler to forward requests starting from /resources/**. That means that if you relatively request js/app.js, it won't work, since it won't trigger the resource handler. You need to use resources/js/app.js:
<script type="text/javascript" src="resources/js/app.js"></script>
However, if your goal is to just statically serve some HTML pages, it's a lot easier to just put the HTML pages into the src/main/resources/static folder as well. Spring boot already serves the index.html by default as the welcome page but it can be customized.
you have to be careful of overriding any of the defaults
I struggled with connecting my static resources to my jsp pages and this is what I finally used to get it working with Spring boot 2.0. You can see my properties and also what the urls look like when mapping to static resources like images or plain html.
Next we need to define the template prefix and suffix for our JSP files in application.properties. Thus add: (the context path 'pdx' is optional and you can pick a name to match your application)
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
server.servlet.context-path=/pdx
http://localhost:8080/pdx/images/thedocks.jpg access static resources in src/main/resources/static/images/thedocks.jpg
http://localhost:8080/pdx/ loads index.html in src/main/resources/static/index.html
http://localhost:8080/pdx/css/home.css loads css class in src/main/resources/static/css/home.css
http://localhost:8080/pdx/h loads my home controller with #Controller("/") and #GetRequest(“/h”) annotations.
my jsp page loads the static image like this
<img alt="the docks" src="/pdx/images/thedocks.jpg"/>

Composite C1 4.0 Beta and MVC Player outputting 2nd html and body tags

I have setup and installed the Composite C1 4.0 beta, along with the latest MVC Player build (from 12/7/2012 nightly), but whenever I call the MVCPlayer function, it outputs additional tags on the page. For example, I am calling a MVCPlayer function for breadcrums. This is the output:
..... before breadcrum content .....
<a name="site-nav" class="screen-reader"></a>
<html xmlns="http://www.w3.org/1999/xhtml">
<head />
<body>
<html>
<head />
<body>
<!-- START BREADCRUM SECTION -->
<ul id="breadcrumbs">
<li>Homep</li>
<li>Events</li>
</ul>
<!-- END BREADCRUM SECTION -->
</body>
</html>
</body>
</html>
<div class="clear"></div>
</div>
..... rest of page .....
As you can see, it is in the middle of the page. The MVCPlayer is returning an XDocument in the render function. So, how do I get rid of the extra tags before the START & END BREADCRUM SECTION comments? The page renders fine, but this is impacting the ability for me to use a page filter to add additional content to the output, such as switching out image tag src's so I can use a jquery script to perform lazy loading images (see http://www.appelsiini.net/projects/lazyload).
Any thoughts?
Thanks!
Chad
The output of the actual breadcrums page is simply <ul><li>...</li></ul>, and there are no errors in the log files. The MVC Player actually adds the additional code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head />
<body>
</body>
</html>
In the Player.cs file, here is the code:
var sbHtml = new StringBuilder();
sbHtml
.Append(#"<html xmlns=""http://www.w3.org/1999/xhtml"">
<head/>
<body>")
.Append(responseWriter.ToString())
.Append(#"
</body>
</html>");
try
{
return XDocument.Parse(sbHtml.ToString());
}
I was able to modify the /Renderers/Page.aspx.cs and changed this line to "strip" out the extra tags:
Original:
xhtml = _renderingContext.FormatXhtml(xhtml);
Updated:
xhtml = _renderingContext.FormatXhtml(xhtml.Replace(#"<html xmlns=""http://www.w3.org/1999/xhtml"">", "").Replace("<html>", "").Replace("<head />", "").Replace("<head></head>", "").Replace("<body>", "").Replace("</body>", "").Replace("</html>", ""));
I'm sure there is a better solution than this? :)
Chad
It could be that somewhere else on the the page you have markup which makes the whole result document and invalid XHTML, and therefore the system cannot process it correctly.
Try to
a) Check the log files to see if there any related warnings
b) validate the output xhtml http://www.xmlvalidation.com/

what is the right way to write this helper code in cakephp 1.3

i use light box but something wrong with this code to show light-box
instead of
image #1
i use this code for view
$thumb = $this->Html->image('images/thumb-1.jpg');
$full = $this->Html->image('/images/image-1.jpg', array('rel' => 'lightbox'));
echo $this->Html->link($thumb,$full, array('escape' => false));
but i see this error
Error: The action <img src=" is not defined in controller ImagesController
Error: Create ImagesController::<img src="() in file: app\controllers\images_controller.php.
<?php
class ImagesController extends AppController {
var $name = 'Images';
function <img src="() {
}
}
?>
Notice: If you want to customize this error message, create app\views\errors\missing_action.ctp
Translating the instructions:
Lightbox 2 uses the Prototype Framework and Scriptaculous Effects Library. You will need to include these three Javascript files in your
header (in this order).
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="js/lightbox.js"></script>
For Cake that means to put these lines into your default.ctp layout and the Javascript files into the webroot/js folder.
Include the Lightbox CSS file (or append your active stylesheet with the Lightbox styles).
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
Again, put this in the layout and the css file into webroot/css.
Check the CSS and make sure the referenced prev.gif and next.gif
files are in the right location. Also, make sure the loading.gif and
close.gif files as referenced near the top of the lightbox.js file
are in the right location.
Make sure the images are in the right location in webroot/img, adjust paths as necessary.
Add a rel="lightbox" attribute to any link tag to activate the
lightbox. For example:
image #1
In you do this by adding attributes to the link helper:
$this->Html->link('image #1', '/img/images-1.jpg', array('rel' => 'lightbox'));
Since you have not listed any code you tried, so i assume you've not started integration. Check this link, it have what you need:
Lightbox using CakePHP

Resources