#StackBounty: #php #html #css #pdf #dompdf Convert html with styling (css) to pdf using dompdf and PHP

Bounty: 100

I’m having some problems with my code! I am trying to convert my html invoice to a pdf invoice. This is the invoice I’m using: invoice. But when I convert the html to pdf the styles are not applied and the images don’t show.

This is my PHP code to convert the html to a pdf using DomPDF:

<?php
require 'vendor/autoload.php';
// reference the Dompdf namespace

$files = glob("/invoices/*.pdf");

foreach ($files as $file) include_once($file);

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait'); //landscape / portrait

$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('defaultFont', 'OpenSans');

// Render the HTML as PDF
$dompdf->render();

$output = $dompdf->output();
file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/invoices/" . $order_id . ".pdf", $output);

I think my problem lies with the HTML code.

The problem with the css

I’ve tried a couple of things but none of these worked for me! Here’s what I tried:

Try 1

I’ve tried adding the css with a link tag like this:

$html .= '<link type="text/css" href="/absolute/path/to/pdf.css" rel="stylesheet" />';
I’ve also tried adding the link like a normal (in the head of the file), but both these times I didn’t got it working.

Try 2

I’ve also tried putting the css in a style tag in the head like this:

<style>
    /* my css here */
</style>

This didn’t work eighter. I’m running out of ideas for the css.

The problem with the images

When the html code contains a img like this:

<img src="/path/to/file" alt="" />

The image doesn’t show up. Not even when I change the src to https://pathtoimg.com/path/to/file/img.png

Hopefully, you know the solution to the image and the css problems I’m struggling with! Thanks already for your effort!


Get this bounty!!!

#StackBounty: #php #html #laravel #laravel-blade #utf8mb4 HTML Special Characters and Emojis Showing up Incorrectly on Laravel Webpage

Bounty: 100

I am likely doing something silly and thought this would be pretty straightforward. I am pulling data from an external API and storing it right into the database via Eloquent model’s I am creating/saving.

The data saved into the database field looks like this:
I Can't Believe It's A – The field is using utf8mb4_unicode_ci collation.

My webpage has the following meta data:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

And I am displaying it via my Laravel blade template like so:

<td>{{ $company->type->name }}</td>

I am a bit confused what I am doing wrong here? From the documentation and other stackoverflow questions I appear to be doing it correctly. My config/database.php has the following:

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => 'InnoDB',
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

I believe this is all correct. Is there something I am missing here? Switching to use the unescaped {!! !!} seems to result in the content still being displayed the same. I am using Laravel v7.13.0

Also Google Chrome reports it is UTF-8 rendered:

> document.characterSet
"UTF-8"

Edit:

Here is an example of getting the response and what the returned JSON name looks like:

>>> $response = Http::withOptions(
            [
                'verify' => false,
                'base_uri' => config('custom.torn_api_base'),
                'timeout' => 5.0
            ]
        )->get(
            "company/79831",
            [
                'selections' => 'profile',
                'key' => config('custom.torn_api_key')
            ]
        );
=> IlluminateHttpClientResponse {#3393
     +"cookies": GuzzleHttpCookieCookieJar {#3379},
     +"transferStats": GuzzleHttpTransferStats {#3418},
   }

>>> $response->json()['company']['name'];
=> "👾 Button Mashers™"

^ You can see above their API is giving me the same string with the UTF-8 encoding that would be used on their website.

Here is me creating and saving the model to the database:

            $company = Company::updateOrCreate(
                [
                    'id' => $tornPlayerData['job']['company_id']
                ],
                [
                    'name' => $tornPlayerData['job']['company_name'],
                    'player_id' => $this->player->id,
                    'isOwner' => true
                ]
            );

I also am logging the response and here is what one of the lines with an Emoji looks like:

Log::info("Updating company '{$company->name}'' now", ['company' => $company]);

laravel.log│[2020-06-22 00:43:52] staging.INFO: Updating company '👾 Button Mashers™'' now {"company":{"App\Company":{"id":79831,"name":"👾 Button Mashers™","player_id":2141091,"updated_at":"2020-06-22T04:43:52.000000Z","created_at":"2020-06-22T04:43:52.000000Z"}}}

Edit 2:
I just manually copied and pasted the Tinker output of 👾 Button Mashers™ to name in the associated database row. Now the website displays that manually adjusted one properly. So it seems Laravel is doing something weird to the data from the API when it is storing it and I am unsure why that would be.

Edit 3:

Using the HEX query as the user asked in the answer.

SELECT id,name,HEX(name) FROM `companies` WHERE id=60335

(60335, 'Pokey's Play House!', '506F6B657926233033393B7320506C617920486F75736521');

(60335, ''', '26233033393B');

The second result is with me modifying the Pokey's Play House! to just ' so you can see the result of just the apostrophe.

Edit 4:

The blade template:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Company Directory</title>

        <!-- Fonts -->
{{--        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">--}}

        <!-- Styles -->
          ** Snipped some minor CSS away from here **
        </style>
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">

        <!-- Scripts -->

        https://code.jquery.com/jquery-3.5.1.slim.min.js
        https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js
        <script type="text/javascript" charset="utf8">
            **removed some datatables code from here for this paste**
        </script>

    </head>
    <body>
        <table id='directory-table' class='display'>
            <thead>
                <tr>
                    <th>Player Name</th>
                    <th>Company Name</th>
                    <th>Type</th>
                    <th>Rank</th>
                    <th>Positions</th>
                </tr>
            </thead>
            <tbody>
                @forelse ($companies as $company)
                    <tr>
                        <td>
                            <a href='https://www.example.
net/profiles.php?XID={{ $company->player->id }}'>
                                {{ $company->player->name }}
                            </a>
                        </td>
                        <td>
                            <a href='https://www.example.net/joblist.php#/p=corpinfo&userID={{ $company->id }}'>
                                {{ $company->name }}
                            </a>
                        </td>
                        <td>{{ $company->type->name }}</td> //THIS IS THE PROBLEM STRING HERE BEING OUTPUTTED
                        <td> {{ $company->rank }}</td>
                        <td> {{ $company->hired_employees }}/{{ $company->max_employees }}</td>
                    </tr>
                @empty
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                @endforelse
            </tbody>
        </table>
    </body>
</html>


Get this bounty!!!

#StackBounty: #javascript #python #html #css #django Favorite system in Django

Bounty: 50

Image

enter image description here

$(document).ready(function(){
    $(".like").click(function(){
        $(this).toggleClass("heart");
    });
});
.like {
  padding-right: 6px;
  color: #00000030;
  font-size: 1.6em;
  padding-top: 5px;
  animation: like 0.5s linear;
}

.heart {
  color: #FF0000;
  animation: heart 0.5s linear;
}
{% for m in musicl %}
  <div class="card">
        <div class="top">
          <div class="year">{{m.Year}}</div>
          <span class="like"><i class="fa fa-heart"></i></span>
        </div>

        <div class="middle">
          <a href="https://google.com" id="link" target="_blank">
            <div class="img-container"><img src="{{ m.Image.url }}"></div>
          </a>
        </div>

        <a href="https://google.com" id="link" target="_blank">
          <div class="bottom">
            <div class="title">{{m.Name}}</div>
            <div class="genre">{{m.Genre}}</div>
          </div>
        </a>
  </div>
{% endfor %}

models.py

class Music(models.Model):
    Name = models.CharField(max_length=100, blank=False)
    Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
    Genre = MultiSelectField(choices=GENRE_CHOICES)
    Image = models.ImageField(blank=False, null=True)

    def __str__(self):
        return self.Name

Views.py

def home(request):
    return render(request, template_name='main/home.html', context={"musicl": Music.objects.all})


def wishlist(request, id):
    pass

How do I connect the User model to this favorite system and keep track of the favorite list in a view function(wishlist), in other words when someone clicks on the fav icon, I want that specific card to be saved to the wishlist view corresponding to that User model


Get this bounty!!!

#StackBounty: #java #html #css #bootstrap-4 is there a way to prevent repeating code in html I'm using bootstrap 4 collapse like 20…

Bounty: 50

    <div class="card" style>
      <div class="card-header" id="headingOne">
        <h5 class="mb-0">
          <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria- 
expanded="true" aria-controls="collapseOne">
                          Collapsible Group Item #1
                      </button>
        </h5>
      </div>
      <!-- Add mx-auto -->
      <div id="collapseOne" class="collapse show text-center mx-auto" aria-labelledby="headingOne" 
 style="width:300px;">
        <div class="card-body">
          <div class="card">
            <div class="card-header text-center" id="headingTwo" style="width:300px;">
              <h5 class="mb-0">
                <button class="btn btn-link collapsed text-center" data- toggle="collapse" data- 
   target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo" style="width:300px;">
                                      Collapsible Group Item #2
                                  </button>
              </h5>
            </div>
            <div id="collapseTwo" class="collapse show" aria-labelledby="headingTwo">
              <div class="card-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus wolf moon put a 
                craft beer sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings farm-
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="card-header" id="headingThree">
        <h5 class="mb-0">
          <button class="btn btn-link collapsed" data-toggle="collapse" data- target="#collapseThree" 
 aria-expanded="false" aria-controls="collapseThree">
                          Collapsible Group Item #3
                      </button>
        </h5>
      </div>
      <div id="collapseThree" class="collapse" aria-labelledby="headingThree">
        <div class="card-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry wolf moon 
          et. Nihil anim keffiyeh helvetica, craft beer labore wes sapiente ea proident. Ad vegan 
        </div>
      </div>
    </div>
  </div>

Hello I have been copying and pasting this like 10-20 times on my code changing the id the header id and the button. I also had been copying and pasting a bunch of other html code (image tag about 20 images) I was wondering if there was a way to stop repeating code (like a function) with pure html css. If not can you do it with plain vanilla js? if not then what are the other ways?

In short

Most important question (A is most important C is least)

  • A) is there a way to prevent repeating code with the collapse code
    above with just pure HTML/CSS? if yes how?
  • B) is there a way to prevent repeating code with the collapse code
    above with just pure HTML/CSS/vanilla js? if yes how?
  • C) is there a way to prevent repeating code with the collapse code
    above with just pure HTML/CSS/angular/react? if yes how?


Get this bounty!!!

#StackBounty: #javascript #html #css #responsive-design #flexbox How to control the height of descendant box within a nested flexbox co…

Bounty: 50

.main {
  height: 100px;
  width: 100px;
  border: 1px solid;
  background: green;
}
.columns {
  display: flex;
}

.columns.vertical {
  flex-direction: column;
  flex-wrap: nowrap;
}

.box22 {
  overflow: auto;
}
.box1 {
  background: red;
}
.box2 {
  background: orange;
  border: 1px blue solid;
}
.box222 {
  background: white;
  border: 1px blue solid;
}
<md-content class="md-padding">
  <div class="main columns vertical">
    <nav class="box1">nav</nav>
    <div class="box columns vertical">
      <div class="b">asdasd</div>
      <div class="box2 columns vertical">
        <div class="box21 columns">
          box21
        </div>
        <div class="box22 columns">
          <div class="box221">box221</div>
          <div class="box222">
            <p>a</p>
            <p>a</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</md-content>

I manually set the height of outermost box main and also set box22 with overflow:auto, however the box22 stretched out the main box and no scroll bar shows up.

What I want is to set height in the outermost box and the nested inner box can automitically control it’s height thus all boxes are fitted. How to fix these kind of problem, should I set heights for all descendant boxes?

I tested setting overflow :auto at box(level1), box2(level2) and box22(level3), only box(level1) can automatically control it’s height and shows up a scroll bar when it’s height overlayed.

what I want is shown below, however, to achieve this, I need to manually specify the father box of box22. In other words, if I want to make a flex contaner scrollable, I have to at least set it’s father box’s height, which is toally unaccptable.

.main {
  height: 100px;
  width: 100px;
  border: 1px solid;
  background: green;
}
.columns {
  display: flex;
}

.columns.vertical {
  flex-direction: column;
  flex-wrap: nowrap;
}
.box22 {
  overflow: auto;
}
.box1 {
  background: red;
}
.box2 {
  height:64px;
  background: orange;
  border: 1px blue solid;
}
.box21 {
  background: yellow;
}
.box222 {
  background: white;
  border: 1px blue solid;
  margin-top: auto;
}
<md-content class="md-padding">
  <div class="main columns vertical">
    <nav class="box1">nav</nav>
    <div class="box columns vertical">
      <div class="b">asdasd</div>
      <div class="box2 columns vertical">
        <div class="box21 columns">
          box21
        </div>
        <div class="box22 columns">
          <div class="box221">box221</div>
          <div class="box222">
            <p>a</p>
            <p>a</p>
            <p>a</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</md-content>


Get this bounty!!!

#StackBounty: #javascript #html #mdc-components MDC menu – keep menu open when focus is on input

Bounty: 50

I am building an autocomplete input using mdc web components. I have an input textfield and a menu. You can see the codesandox here.
I am showing the menu on focusin event, but if I start writing in the input field the menu is closed immediately.

const input = new MDCTextField(document.querySelector(".mdc-text-field"));
const menu = new MDCMenu(document.querySelector(".mdc-menu"));

input.listen("focusin", () => (menu.open = true));

I assume that is because of the menu default behaviour to close when click outside of the menu is triggered. The problem here is also that focus is taken by the first menu item from the textfield. What would be the way to prevent that, and have menu open until the focus is lost on the input field?


Get this bounty!!!

#StackBounty: #html #css #iframe #bootstrap-4 #containers Bootstrap embed responsive is not formatted well for mobile browser in landsc…

Bounty: 50

I am using the latest version of bootstrap and included the responsive embed for my youtube videos with the bootstrap container. The container sizes the video well within the constraints on the container however, the video looks very large while in landscape, taking up too much space. I think this is becuase the bootstrap container class changes its width based on media-queries which works fine for mobile devices in portrait but not well for mobile devices in landscape. Here is the standard code that I am using:

https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js
<main id="content-wrapper" class="container">
  <div class="embed-responsive embed-responsive-16by9">
    https://www.youtube.com/embed/
  </div>
</main>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js

Is there any way that I can fix the container so that it improves the formatting of the video in landscape?


Get this bounty!!!

#StackBounty: #android #html #google-chrome #service-worker #progressive-web-apps How to avoid local web app data being erased?

Bounty: 100

We’d like to have our web app available offline, mainly on mobile devices. We’ve written code for that, using a service worker. Application data is stored in an IndexedDb and the application code (html, js, css, etc) is stored in the SW cache. So far so good. We are aware that the user can delete the browser cache and our data, that’s not a problem. But what about the browser itself wiping the app data ? We haven’t found a comprehensive specification for that, the main info we found are:

1) the StorageManager feature that is currently marked as “experimental” (since 2016);

2) a short article from Google here about it (also from 2016).

The code sample is the following:

if (navigator.storage && navigator.storage.persist)
  navigator.storage.persist().then(granted => {
    if (granted)
      alert("Storage will not be cleared except by explicit user action");
    else
      alert("Storage may be cleared by the UA under storage pressure.");
  });

The Google article says:

When storage on the local machine is running tight (“under storage
pressure”), user agents automatically clear storage to make more
available space. Of course, for offline apps, this may be unfortunate,
as they may not have synced their data to the server yet, or they may
be apps that the user expects to just work offline (like a music
player); so the Storage spec defines two different modes for storage
for a given domain – “best effort” and “persistent”. The default mode,
of course, is “best effort”. Storage for a domain that is “best
effort” (aka “not persistent”) can be cleared automatically, without
interrupting or asking the user. However, “persistent” data will not
be automatically cleared. (If the system is still under storage
pressure after clearing all non-persistent data, the user will need to
manually clear any remaining persistent storage.)

Beginning with Chrome 55, Chrome will automatically grant the persistence
permission if any of the following are true:

  • The site is bookmarked (and the user has 5 or less bookmarks)
  • The site has high site engagement
  • The site has been added to home screen
  • The site has push notifications enabled

The permission is automatically denied in all other cases.

The goal is to ensure that users can rely on their favorite web apps
and not find they have suddenly been cleared.

That’s for Chrome 55, let’s suppose the information is up to date. A first glance, their goal sounds reasonable, but if you take a closer look the implementation is geared for “big” sites (à la Google) and not for niche applications that are more task-oriented.

Indeed, when testing on various Android phones on Chrome 80+, the persistence is always refused, with no user interaction. So, “best effort” it is.

We could have stopped the investigation here and called it a day. After all, current phones and PC are sporting ungodly amount of storage, and we only use a few hundred of KB, so we should be fine. Problem is, we’re not: testing on a brand new flagship Android phone with Chrome, our code is erased only with a few seconds of fiddling (closing and opening the page a few times is enough). On other platforms it’s different, but Android+Chrome will get the most use.

Oddly, only the code in the SW cache (<100KB) is erased, and the bigger IndexedDb is not. So we tried to also put the code in the IndexedDb, and it seems more “persistent” that way, but the code to manage that is also more involved, so it feels somewhat hackish.

Are we alone with that problem ? If not, how are you people dealing with it ?

Bonus question: is there more up to date documentation on the subject somewhere ?


Get this bounty!!!